我正在使用 Bluebird对于 Node.Js 中的 promise ,并且想知道如何在 promise 履行(完成)时让函数返回。我想要的行为是:
function getItem(){
functionReturningPromise.then(function(result){
//do some operation on result
return result;
});
}
但是,上述实现不会返回任何内容,因为在执行时未完成 promise 。解决此问题的最佳解决方法是什么?
getItem的目的是修改functionReturningPromise返回的任何东西,然后返回
最佳答案
你不能,var value = someAsyncFunction()
是不可能的(至少在我们有生成器之前)。 Promise 是病毒式的,一旦你在函数中使用 Promise,它的调用者必须使用 then
和调用者的调用者,等等直到你的主程序。因此,在调用 getItem
的函数中,您必须更改它
item = getItem();
do something with item
进入这个
getItem().then(function(item) {
do something with item
})
和 getItem
也应该返回一个 Promise
function getItem(){
return functionReturningPromise().then(function(result){
//do some operation on result
return result;
});
}
(理论上它也可以是回调,但我更喜欢总是返回 promise )。
关于javascript - promise Js : Wait till promise fulfilled,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35785024/