Promise到底是个什么

Promise

平时我们发起异步请求会去调用回调函数,在回调函数中我们无法使用return和throw来处理代码,Promise可以解决这个现象。

首先,Promise是一个对象。

它用于一个异步操作的最终完成以及返回值的表示,如果我们console.log一下会发现他是一个构造函数,自己有all,reject,resolve等方法,原型链上有then和catch等方法。

new Promise( function(resolve, reject) {...} /* executor */  );

这个函数参数,有两个参数一个是成功的回调,一个是失败的回调。

let p1 = new Promise((resolve,reject) =>{
  resolve(someValue);
  //rejcet("failure reason");
});
-----------------------------------------------------------------
//这里注意,代码到这里只是new了一个对象,但是他已经开始执行了,所以一般是把Promise包在一个函数中,实现调用后再执行的效果。
p1.then(function(success){},function(error){}).catch(function(reason){
  console.log("the reason of error is ",reason);
});
//下面的代码就是then()和catch的语法结构,下面会稍微深入的讲解一下。

之前说过,回调函数剥夺了return and throw,那我们现在用Promise把他们抢回来。

function test(){
    var p1 = new Promise(function(resolve, reject){
        //模拟异步操作
        setTimeout(function(){
            resolve('string');
        }, 500);
    });
    return p1;            
}
p1.then().catch();

普通的回调可能也一样执行,就像这样

function test(resolve){
  setTimeout(function(){
    resolve('string');
  }, 500);           
}
test(function(data){
    console.log(data);
});

如果有多层的时候,这样就不适用了,可以使用链式结构。

test.then(rst=>{
  return test1();  //返回一个Promise,可以继续调用then()方法
}).then(rst1=>{
  return test2();  //又返回一个Promise,每个Promise默认调用resolve()来调用then的第一个方法。
}).then(rst2={
  console.log(rst2)
}).catch(err=>{
  console.log(err);
})

如果调用的是Promise的reject()方法,就要调用then的第二个方法了,顺便还会走一下catch()方法,他会自动给reject抛出一个错误。由于都会走同一个路线,通常只写then()方法的第一个参数,然后加上catch()这样更简洁。reject()方法等同于抛出错误。

fetch

我们平时使用的fetch就是封装的Promise,fetch后面直接跟then,作为参数的函数接收要给参数,参数是fetch返回的信息(response)。这里要注意,response.json()也是需要.then才能得到结果的(异步),使用async关键字的时候也要记得加上await.

猜你喜欢

转载自blog.csdn.net/run_youngman/article/details/78780620
今日推荐