Promise知识点

1.promise对象用于异步计算,表示一个现在,将来或者永不可能用的值;即将异步操作队列化,按照我们期望的先后顺序执行,返回符合预期的结果;

2.js包含了大量的异步操作,所以需要promise;比较形象的例子就是去餐厅点餐,服务员的同步服务和异步服务的区别;

3.promise实例:

(1)

​​​​​​​new Promise(
    function(resolve,reject){
         resolve();   //数据成功处理完成
         reject();    //数据处理错误

    }
).then(function A(){},function B(){})    //数据成功处理下一步执行A,否则下一步执行B函数
 .then()      //再下一步,如此循环; 里面可以用return value 将最初的new Promise里面的值一级
                         //一级的向下传递

(2)

new Promise(resolve=>{
    resolve("这是数据成功处理返回的数据")
}).then(value=>{
    console.log(''这个"+value+"是then()再上面resolve返回的值")
})

(3)

let p=new Promuse(resolve=>{
  resolve("值")    
});

p.then(value=>{       
  console.log(value)    //这里仍然可以输入let p返回的resolve的值;
})

4. .then()的四种执行顺序:

5. 错误处理:两种方法;

(1) 

new Promise({
   throw new Error("第一种promise错误处理")

}).then(value=>{console.log(value)})     //new Promise()实例视为有错误,不会执行.then()
  .catch(err=>{console.log(err)})    //而是执行.catch(),其会抓住之上new Promise()和.then()里
                                    //面所有的错误

(2) 

new Promise({
   reject("第二种promise错误处理")
}).then(value=>{
   console.log(value)
},err=>{
   console.log(err)     // 会执行.then()里面的第二个函数 ,不会执行第一个函数
})    

   6.cath()的链式处理:

new Promise({
   resolve();
}).then(()=>{
      console.log("这是是处理promise实例的值")
      throw new   Error("再then()扔出一个错误")
}).catch(err=>{
      console.log(err)    //处理支此以上所有的错误
      throw new Error("再这扔出一个错误")
}).then(()=>{ 
      console.log("其全面的catch是否有throw new Error将决定本then()是否执行")
}).catch(err=>{
      console.log(err)    //如果上一个catch()有throw new Error(err)就不会执行这2个cath()之间的
      then(),否则就不会执行这个catch()
})

猜你喜欢

转载自blog.csdn.net/qq_42231156/article/details/84562970
今日推荐