async/await ,Blurbird Promise,原生Promise学习小结。

最近在研究node+koa构建服务端,在数据库方面我选择了sequelize。于是乎就碰到了个问题,sequelize文档说它是使用Bluebird Promise来控制流程。那么Bluebird Promise和原生Promise 有什么差别呢?在使用async/await进行异步执行的时候会有什么不同的影响吗?带着这些问题,我开始了为期一个下午加一个早上的摸索。

首先我先想测试下Bluebird Promise 和 原生Promise执行有什么差别,于是我使用sequelize来获取bluebird的promise

     const bluePromise = require('bluebird');

     let bP = new bluePromise((r)=>{r(8)}); // 返回的是Bluebird Promise对象
     bP.then(r=>{
            console.log("bluebird: "+r);
        });


    new Promise(resolve=>{resolve(192)})  // 原生Promise对象
        .then(r=>{
            console.log("native promise: "+r);

        })
        
    console.log("end");

看到这段代码,如果Bluebird Promise与原生Promise没差别那么打印顺序应该是 end   bluebird:8   native promise:192,

可是实际结果是 end native promise : 192   bluebird:8

没错,Bluebird的then操作在原生promise的后面。通过我查阅帖子了解到,Bluebird的then操作放在宏任务队列,而原生Promise属于微任务队列,所以这就好理解了。

接下里看 await 后面跟着这两种Promise对象的时候会有什么差异呢?

根据ECS文档上说 await 后若为promise对象,它会等待promise返回值后再继续执行下面的代码。

const bluePromise = require('bluebird');
const test = async ()=>{

     let bP = new bluePromise((r)=>{r(8)}); // 返回的是Bluebird Promise对象
     await bP.then(r=>{
            console.log("bluebird: "+r);
        });


     await new Promise(resolve=>{resolve(192)}) 
        .then(r=>{
            console.log("native promise: "+r);

        });

     console.log("end");
}

结果: bluebird:8   native promise:192  end

那么证明了Blurbird Promise与原生Promise在await 关键字后方都被作为promise,await都会等待其执行结束返回一个值(若最后一个then没有return值则返回undefined)后再执行下一步的代码。与Bluebird Promise 和原生Promise的差异没有什么关系。

猜你喜欢

转载自blog.csdn.net/qq_37028216/article/details/84135063