承诺不等待完成

Ada*_*dam 3 javascript promise ecmascript-6

我今天看了很多例子.他们似乎建议在链中执行以下代码:

let f = () => {
    return new Promise((res, rej) => {
        console.log('entering function');
        setTimeout(() => {
            console.log('resolving');
            res()
        }, 2000)
    });
};

Promise.resolve()
    .then(f())
    .then(f());
Run Code Online (Sandbox Code Playgroud)

预期产出将是:

entering function
resolving
entering function
resolving
Run Code Online (Sandbox Code Playgroud)

但事实并非如此.输出是

entering function
entering function
resolving
resolving
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚为什么.任何帮助都感激不尽.

小智 11

尝试then(f)而不是then(f())

then 期待一个功能.

你也可以 then(()=>f())

  • 额外的帮助,调用`then(f())`立即调用函数 (2认同)