承诺不等到完成 [英] Promise not waiting to finish

查看:85
本文介绍了承诺不等到完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I looked at many examples today. They seem to suggest that the following code should be executed in chain:

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

,我不知道为什么.任何帮助将不胜感激.

and I can't figure out why. Any help will be much appreciated.

推荐答案

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

then需要一个功能.

您也可以执行then(()=>f())

这篇关于承诺不等到完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆