承诺不等待完成

3

今天我看了很多例子。它们似乎表明以下代码应该按顺序执行:

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

Promise.resolve()
    .then(f())
    .then(f());

预期输出应该是:
entering function
resolving
entering function
resolving

但事实并非如此。输出结果为:
entering function
entering function
resolving
resolving

我不明白为什么发生了这种情况。非常感谢您的帮助。

1个回答

12

使用then(f)代替then(f())

then需要一个函数作为参数。

您也可以使用then(()=>f()).


2
额外的帮助,调用then(f())会立即调用该函数。 - Cjmarkham

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接