【发布时间】:2016-05-13 16:48:32
【问题描述】:
我在某个项目中使用 Promise 已经有一段时间了。 它的大部分语法都很容易理解,但今天我发现了一个奇怪的行为。
据我所知,Promise 也可以处理 then 方法的返回,如果它也是“thenable”的话。
我对以下两种情况感到非常困惑,为什么第二种情况会出现这种行为......
// right
// show the message exact like expect
'use strict';
const startPrompt = () => {
const questionPromise = new Promise((resolve) => {
setTimeout(() => {
console.log('first 2');resolve();
}, 2000);
}).then(() => {
return new Promise((resolve) => {
setTimeout(() => {
console.log('second 2');resolve();
}, 2000);
})
});
return questionPromise;
}
startPrompt().then(() => console.log('end'))
// wrong
// the second 'then' and the third 'then' method execute at the same time
'use strict';
const startPrompt = () => {
const questionPromise = new Promise((resolve) => {
setTimeout(() => {
console.log('first 2');resolve();
}, 2000);
});
questionPromise.then(() => {
return new Promise((resolve) => {
setTimeout(() => {
console.log('second 2');resolve();
}, 2000);
})
});
return questionPromise;
}
startPrompt().then(() => console.log('end'))
【问题讨论】:
-
你必须像
return questionPromise.then(() => {一样返回questionPromise.then(() => { ..,因为它创建了新的Promise对象 -
尝试用
return questionPromise.then(...);返回承诺检查小提琴jsfiddle.net/nuxbox/ufj8gyr1 -
基本上,“第二个 2”代码等待 questionPromise 解决...
console.log('end')也等待 questionPromise 解决,因为这是您从 startPrompt 返回的内容 -
@JaromandaX 抱歉,我在发布之前删除了一些代码,因为我写的原始示例有点长。然后上面两个。
then方法同时执行。
标签: javascript promise ecmascript-6