javascript - resolve 在 Promise 中真正做了什么?
问题描述
我以为我对 Node 和 Promises 有很好的理解,但是当我试图为我的朋友解释一些事情时,我遇到了这个问题。
我的问题是,这个小脚本的预期输出是什么?
const myPromise = new Promise((resolve, reject) => {
console.log("inside promise")
resolve("Lol!")
})
for (let i=0; i<1000000; i++) {}
// just want to be sure that the next line starts after the promise finishes execution
myPromise.then(() => console.log("then!"))
console.log("finished")
我的预期输出:
inside promise
finished
我的想法是,如果承诺在读取之前完成执行myPromise.then(...
,那么日志不应该永远不会出现吗?
实际输出:
inside promise
finished
then!
如果我发出resolve("Lol!")
尽管预期输出与实际输出匹配。
谁能解释一下这里发生了什么?
谢谢!
解决方案
这是您的示例注释:
console.log('Before myPromise is created');
const myPromise = new Promise((resolve, reject) => {
// This is executed immediately when a new
// Promise is created, so it will appear
// BEFORE 'After myPromise is created'.
console.log("Inside promise")
// This passes the value "Lol!" to
// the 'then' function. By itself it
// does not console log anything.
resolve("Lol!")
})
console.log('After myPromise is created');
// This does nothing, code immediately
// carries on executing. After >=100ms a function
// doing nothing is called.
setTimeout(() => {}, 100)
// The 'then' is passed the argument of
// `resolve()` (in this case "Lol!")
myPromise.then(resolveArg => console.log(resolveArg))
// Second to last console log because
// all .then() handlers are called asynchronously
// once the main thread is idle (as the Promises/A+
// spec says, when the JS engine returns back to
// "platform code"). Therefore "Lol!" will be the
// last thing logged.
console.log("Finished")
推荐阅读
- excel - 如何根据单元格值隐藏和取消隐藏行?
- string - 字符串拆分成所有可能的组合
- c# - C#-Linq:在 linq 中使用 string.equals 进行比较时忽略大小写
- c# - 将日期和时间转换为 GMT 格式
- dart - Dart 正则表达式使用 `$1`
- android - 如果数据也在表 B 中,Android SQLite QUERI 从表 A 中检索数据
- laravel - Laravel 错误 - 路线 [appraisal.appraisal_goals.manager_employee_goal/{id?}] 未定义
- reactjs - 刷新当前页面时如何重定向到另一个页面Reactjs
- perl - 我怎么知道钻石操作员是否移动到下一个文件?
- firebase - Firebase 实时数据库协议开销和 SSL 加密开销