为什么Promise的输出不是“1 2 3”而是“1 3 2”?

时间:2016-03-05 02:20:52

标签: javascript

a = function() {
    return new Promise(function(resolve, reject) {
        console.log(1);
        resolve('next');
    }).then(function() {
        console.log(2);
        return;
    });
};

b = function() {
    console.log(3);
};

a().then(b());

我认为在解决“next”之后,它将调用输出“2”的函数,我无法理解为什么“console.log(3)”首先发生(异步?)。我想知道哪一部分我误解了关于Promise的用法。

2 个答案:

答案 0 :(得分:5)

a().then(b());

调用a,设置承诺。在构造函数中设置时会记录1。执行b后会调用b(),从而记录3。您传递给then的内容不是b函数,而是通过调用bundefined返回的结果。然后,当您解析承诺时,它会记录2

您的代码应该是“1 2 3”。

a().then(b);

答案 1 :(得分:2)

你可能想写a().then(b)。通过撰写a().then(b()),您在致电b()之前致电 then

相关问题