承诺`then`,函数不返回任何内容,而函数返回另一个承诺 [英] Promise `then` with a function returning nothing vs with a function returning an another promise

查看:66
本文介绍了承诺`then`,函数不返回任何内容,而函数返回另一个承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么我们执行这段代码会有如此奇怪的结果.

为什么没有 12121212 的图像?在每个 1 之后,我们有三个 2.

I can't understand why we have such a strange result of execution this code.

Why isn't there an image of 12121212? And after each 1 we have three 2.

Promise.resolve()
.then(() => { console.log(1); return Promise.resolve(); })
.then(() => { console.log(1); return Promise.resolve(); })
.then(() => { console.log(1); return Promise.resolve(); })
.then(() => { console.log(1); return Promise.resolve(); })
.then(() => { console.log(1); return Promise.resolve(); })
.then(() => { console.log(1); return Promise.resolve(); })
.then(() => { console.log(1); return Promise.resolve(); })
.then(() => { console.log(1); return Promise.resolve(); });

Promise.resolve()
.then(() => { console.log(2); })
.then(() => { console.log(2); })
.then(() => { console.log(2); })
.then(() => { console.log(2); })
.then(() => { console.log(2); })
.then(() => { console.log(2); })
.then(() => { console.log(2); })
.then(() => { console.log(2); });

推荐答案

这是因为在用另一个 promise 解决 promise 时涉及多个滴答声.

It's because there are multiple ticks involved in resolving the promise with another promise.

但实际上,您应该忽略这一点,永远不要依赖于独立承诺链之间的时间.

But really, you should ignore this, and never rely on timings between independent chains of promises.

这篇关于承诺`then`,函数不返回任何内容,而函数返回另一个承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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