javascript - 输出顺序涉及到promise,js中的微任务队列
问题描述
new Promise((resolve, reject) => {
console.log("promise1")
resolve()
}).then(() => {
console.log("then11")
new Promise((resolve, reject) => {
console.log("promise2")
resolve()
}).then(() => {
console.log("then21")
}).then(() => {
console.log("then23")
})
}).then(() => {
console.log("then12")
})
上面的代码输出如下,当我用 promise 测试我对微任务和宏任务的理解时,我无法得到正确的输出。
// "promise1"
// "then11"
// "promise2"
// "then21"
// "then12"
// "then23"
更具体地说,我对最后 3 个输出感到困惑。谢谢您的帮助!
// "then21"
// "then12"
// "then23"
解决方案
如果您正在寻找此输出:
// "promise1"
// "then11"
// "promise2"
// "then21"
// "then23"
// "then12"
然后在你的 first 中返回 Promise .then(
,如下所示:
new Promise((resolve, reject) => {
console.log("promise1")
resolve()
}).then(() => {
console.log("then11")
return new Promise((resolve, reject) => {
console.log("promise2")
resolve()
}).then(() => {
console.log("then21")
}).then(() => {
console.log("then23")
})
}).then(() => {
console.log("then12")
})
在您的second 之后返回链return
中最后一个所做的 Promise 。您的最后一个将等待 ,然后执行。.then(
new Promise
.then(
then23
.then(
推荐阅读
- node.js - 如何在节点中使用国家标志并做出反应
- php - PHP - 如何获取 OAuth 2.0 令牌
- ios - 在 Xcode 中创建带有标题的大导航栏
- javascript - API调用通过服务器端代码(node.js,php)而不是通过浏览器中的JS使用fetch()
- java - 防止eclipse修剪jsp页面中的空格
- c++ - cl 生成的可执行文件第一次运行非常慢
- python - UnrecognizedImageError - 图像插入错误 - python-docx
- php - 将eregi更改为preg_match后系统停止工作
- javascript - 我需要一个按钮,仅在特定日期的特定时间
- kubernetes - 从文件创建 kubernetes configmap 时,key 是什么意思