在Promise中承诺:从子Promise返回变量的正确方法是什么?(JS) [英] Promise inside promise: what's the correct way to return a variable from the child promise? (JS)
问题描述
我具有这样的功能:
function top() {
//promise1
ParentPromise({
...some code here...
}).then(function() {
//promise2
ChildPromise({
..some code here...
}).then(function(response) {
var result = response.result.items;
});
});
};
并且我需要以这种方式返回结果值:
and i need to return result value in this way:
var myresult = start();
我该怎么做?THX
推荐答案
promise的定义是,您不能从字面上将 result
分配给 myresult
.但是,您可以使 myresult
是一个承诺,该承诺可以直接为调用者解析为 result
,但是使用了许多promise.基本思想是,在上面的代码块中的每个函数内部,您应该返回
链中的下一个Promise.例如:
The definition of promises is that you cannot literally assign result
to myresult
. However, you can make myresult
a promise that resolves directly to result
for the caller, however many promises were used to get that. The basic idea is that inside of each function in your above block, you should be return
ing the next Promise in the chain. eg:
function top() {
//promise1
return ParentPromise({
...some code here...
}).then(function() {
//promise2
return ChildPromise({
..some code here...
}).then(function(response) {
var result = response.result.items;
return result;
});
});
};
最后,调用 top()
的代码将不知道或不在乎使用1个,2个或12个链式承诺来获取结果
.如果这些承诺中的任何一个失败,它也将能够注册一个错误回调.
In the end, the code calling top()
won't know or care that 1, 2, or 12 chained promises were used to get result
. It will also be able to register an error callback in case any of those promises failed.
这篇关于在Promise中承诺:从子Promise返回变量的正确方法是什么?(JS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!