var po = new Promise(function(res,rej){
res(1);
console.log(12)
console.log(123)
}).then(function(data) {
console.log(data);
})
结果是:
12
123
1
对于这个执行结果,有以下疑问:
为什么先输出12和123,再执行了res(1)?Promise中的回调是天然异步的么?(即使new Promise的参数明明是一个同步的函数)
var po = new Promise(function(res,rej){
res(1);
console.log(12)
console.log(123)
}).then(function(data) {
console.log(data);
})
结果是:
12
123
1
对于这个执行结果,有以下疑问:
为什么先输出12和123,再执行了res(1)?Promise中的回调是天然异步的么?(即使new Promise的参数明明是一个同步的函数)
不是执行res,而是抛出res中的值在后续的then()中执行,你这边抛出的是1,所以在promise中代码依次运行完后 会将1抛出,then接受一个函数,这个函数中的参数data就是promise中抛出的值(你这边是1),所以1是被最后打出
10 回答11.2k 阅读
5 回答4.8k 阅读✓ 已解决
4 回答3.1k 阅读✓ 已解决
2 回答2.8k 阅读✓ 已解决
3 回答4.9k 阅读✓ 已解决
1 回答3.2k 阅读✓ 已解决
3 回答2.3k 阅读✓ 已解决
蒋整个流程当做一个tick,Promise 的 then 应当会放到当前 tick 的最后。可以看看这篇文章:https://zhuanlan.zhihu.com/p/...