关于Promise的奇怪行为

时间:2016-02-04 07:20:52

标签: javascript promise ecmascript-6

我曾在一些项目中使用过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'))

1 个答案:

答案 0 :(得分:0)

真的在第二个版本中你有两个 promisses

第一

cd build
./data/mnist/get_mnist.sh
./examples/mnist/create_mnist.sh

你从功能中返回这个,
第二个:

const questionPromise = new Promise((resolve) => {
    setTimeout(() => {
        console.log('first 2');resolve();
    }, 2000);
});

只是在函数内部运行。

mdn中你可以看到

  

then()方法返回Promise 。它需要两个参数:Promise的成功和失败案例的回调函数。

所以,这两个不同的承诺,只是在同一时间运行。