从承诺返回 then() [英] Return from a promise then()
问题描述
我有一个这样的 javascript 代码:
I have got a javascript code like this:
function justTesting() {
promise.then(function(output) {
return output + 1;
});
}
var test = justTesting();
我的 var 测试总是有一个未定义的值.我认为这是因为承诺还没有解决......有没有办法从承诺中返回一个值?
I have got always an undefined value for the var test. I think that it is because the promises are not resolved yet..there is a way to return a value from a promise?
推荐答案
当你从 then()
回调中返回一些东西时,这有点神奇.如果您返回一个值,则使用该值调用下一个 then()
.但是,如果您返回类似 promise 的内容,则下一个 then()
会等待它,并且仅在该 promise 稳定(成功/失败)时才会调用.
When you return something from a then()
callback, it's a bit magic. If you return a value, the next then()
is called with that value. However, if you return something promise-like, the next then()
waits on it, and is only called when that promise settles (succeeds/fails).
来源:https://web.dev/promises/#queuing-asynchronous-actions
这篇关于从承诺返回 then()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!