【问题标题】:A strange behavior about the Promise关于 Promise 的奇怪行为
【发布时间】: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


【解决方案1】:

真的在第二个变体中你有 两个 承诺

第一:

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);
    })
});

只是在函数内部运行。

mdn你可以看到

then() 方法返回一个 Promise。它有两个参数:Promise 成功和失败情况的回调函数。

所以,这两个不同的 Promise 只是同时运行。

【讨论】:

  • 谢谢,很有帮助。
猜你喜欢
  • 1970-01-01
  • 2018-08-28
  • 2016-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-31
  • 2021-10-20
  • 1970-01-01
相关资源
最近更新 更多