await bluebirdPrimose 与await 原生Promise的疑惑求问

Hws有梦想 2018-11-17 12:24:11
最近我一直在学习koa+sequelize,了解到sequelize是基于bluebird的Promise对象编写的。然后就有了下面的疑问。
1.经查阅bluebird的回调是属于宏任务的,原生Promise对象的回调是属于微任务的。await本身属于微任务,那么如果await后面的表达式返回的是一个bluebird的话,为什么和await后面跟着一个原生Promise对象的效果是一样的?


const bluePromise = require('bluebird');

const test = async ctx =>{
await new bluePromise((r)=>{r(8)}).then((r)=>{
console.log("bluebird: "+r);
ctx.body = "bluebird promise";
});

await new Promise(r=>{r(2)})
.then(r=>{
console.log(r);
})
.then(r=>{
ctx.body = "native promise";
});

console.log("end");
};


1. await 后面若是Promise对象则会待promise对象执行完毕才接下去执行。
2. 执行顺序问题。bluebird是宏任务,原生Promise是微任务,这两个不同不影响await的原则。
3. router中间件的函数体中的执行顺序问题。

const test = async ctx =>{
new Promise(r=>{r(2)})
.then(r=>{
console.log(r);
})
.then(r=>{
ctx.body = "native promise";
});
console.log("end");
};

打印得到:
日志: <-- GET /user/test?id=1
end
2
日志: --> GET /user/test?id=1 200 14ms 14b

根据上面代码我猜测router.get/post源代码结构类似于下面代码


async function midware(){
return new Promise(r=>{setTimeout(()=>{r(10)},1000);})
.then(r=>{console.log("p1");})
.then(r=>{console.log("p2");})
}


async function r(){
await midware();
next();
}


请问是否正确
...全文
86 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
Hws有梦想 2018-11-22
  • 打赏
  • 举报
回复
引用 1 楼 啤酒沫 的回复:
await并不是只能用于等待Promise的结果,可以用于任意一个表达式。 MDN上的说明是这样的: [rv] = await expression; expression A Promise or any value to wait for. rv Returns the fulfilled value of the promise, or the value itself if it's not a Promise. 举个例子:

(async ()=>{
  var r= await (()=>{return 3})();
  console.log(r);
})()
其实我主要疑问是await后面跟着一个方法,该方法不返回Promise对象,但是方法里执行promise。在这过程中的一个执行顺序的问题。感兴趣的话可以去我的主页参考下我后面写的一篇博客。还是谢谢你的答复。
啤酒沫 2018-11-22
  • 打赏
  • 举报
回复
await并不是只能用于等待Promise的结果,可以用于任意一个表达式。 MDN上的说明是这样的: [rv] = await expression; expression A Promise or any value to wait for. rv Returns the fulfilled value of the promise, or the value itself if it's not a Promise. 举个例子:

(async ()=>{
  var r= await (()=>{return 3})();
  console.log(r);
})()

87,910

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧