返回前正在函数中收集Q Promise



我有一个使用promise和Q库的函数,本质上我想等到所有promise都被强制执行后再返回,但我的代码只是失败了:

function makeSomething(){
var something = new Something()
Q.all([
somethingPromise1(something)
, somethingPromise2(something)
]).spread(function(resultsFromP1, resultsFromP2){
something.otherValue =  resultsFromP2
}).done()
return something
}
var something = makeSomething()
console.log(something.otherValue)

代码比较复杂,但这是要点。称之为

something = _.find(things, function(){})
if(!something ) something  = makeSomething()

然后

manyMoreInterestingTasks(something)

我不希望我的调用代码必须在if上分叉。本质上,我希望makeSomething在返回之前阻塞太多。我是Node和Q的新手,所以如果我滥用这种方法,我深表歉意。。。

本质上,我希望makeSomething在返回之前也会阻塞。

不可能同步地从Promise中获得结果。othervalue属性是异步创建的,但您将立即返回something。更好:

function makeSomething(){
return Q.all([
somethingPromise1(something),
somethingPromise2(something)
]).spread(function(resultsFromP1, resultsFromP2){
var something = new Something(resultsFromP1);
something.otherValue = resultsFromP2;
return something;
});
}

你需要把你的整个代码承诺!然而,这并不像听起来那么复杂:

// Quite narrative actually (the "then" even was in you question already :-) ):
Q(_.find(things,function(){}) || makeSomething()).then(manyMoreInterestingTasks);
// More verbose version of above:
var something = _.find(things, function(){});
var promiseForSomething = something ? Q(something) : makeSomething();
promiseForSomething.then(function(something) {
manyMoreInterestingTasks(something);
});

// Similar thing within the chain:
Q( _.find(things, function(){}) ).then(function(something) {
// returning either a promise or a plain value from the callback
if (!something)
return makeSomething();
else
return something;
}).then(manyMoreInterestingTasks);

// With explicit error propagation and recovery:
function findSomething() {
var something = _.find(things, function(){});
if (something)
return Q(something);
else
return Q.reject("couldn't find anything");
}
findSomething().catch(makeSomething).then(manyMoreInterestingTasks);

相关内容

  • 没有找到相关文章

最新更新