简体   繁体   中英

Collecting Q Promise in function before returning

I have a function that is using promises and the Q library, essentially I want to wait until all the promises have compelted before returning, but my code is just falling through:

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)

The code is more complicated, but this is the gist. Calling it is more along the lines of

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

then

manyMoreInterestingTasks(something)

I don't want my calling code to have to fork on an if. Essentially I want makeSomething too block until it returns. I am new to Node and Q so I apologize if I am abusing the approach...

Essentially I want makeSomething too block until it returns.

It's impossible to get the result from the Promise synchronously. The othervalue property is created asynchronously, but you're returning something immediately. Better:

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

You need to put your whole code in promises! However, that is not as complicated as it sounds:

// 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM