javascript - promise 链接,顺序错误

标签 javascript promise es6-promise chaining method-chaining

我想了解 Javascript 中的 promise 链。所以我写了这个小 fiddle : https://jsfiddle.net/GarfieldKlon/89syq4fh/

它按预期工作。 c 等待 b,b 等待 a。

但是当我将这些行更改为:

a().then( result => console.log(result))
.then( () => {b().then( result => console.log(result))})
.then( () => {c().then( result => console.log(result))});

所以我在 b 和 c 周围添加了大括号,然后输出是 1, 3, 2。我不明白为什么。

当我添加返回时,它会再次起作用:

a().then( result => console.log(result))
.then( () => {return b().then( result => console.log(result))})
.then( () => {return c().then( result => console.log(result))});

但是为什么呢?当没有花括号时,您只能写一条语句,对吗?而且这个语句是隐式返回的?

当你使用花括号时,你必须显式返回一些东西?

但是为什么使用大括号而不返回时会弄乱顺序呢?为什么当返回丢失时它仍然记录一些东西?

最佳答案

When there are no curly braces you're only allowed to write one expression which is implicitly returned? And when you use curly braces you have to explicitly return something?

Yes .

But why does it mess up the order when using curly braces without return? And why does it still log something when the return is missing?

因为 Promise then 函数依赖于链接的返回值。

请记住then returns a new promise for the result of the callback 。当该结果是另一个 Promise 时,它​​会在履行返回的 Promise(您链接第二个 then() 调用的 Promise)之前等待该内部 Promise 的结果。

如果您的回调开始 b().then(…) 但返回 undefined,则链中的下一步(c() call) 不会等待 b 完成。

关于javascript - promise 链接,顺序错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55236488/

相关文章:

java - 尝试在我的 Play2 应用程序中利用 Akka future 和发挥 promise

javascript - JS Promise 和事件循环执行

javascript - Promise Chaining 和 .then/.catch 语句

javascript - 压缩多个 promise

javascript - 在 Android 应用程序中,单击不起作用。当我单击此链接时。它必须在新窗口中打开

Javascript - 重定向问题

javascript - 从源 'https://js.stripe.com/v2/' 访问位于 'http://localhost' 的 XMLHttpRequest 已被 CORS 策略 : in opencart 阻止

javascript - 填充矩形();即使 x 和 y 是动态的,也只生成一次

javascript - 我怎样才能重写这些 JavaScript promise 而不那么复杂?

javascript - knex.js 查询 "promises"何时执行/解析?