Search code examples
javascriptpromisebluebird

Calling a promise and a non-promise together in Promise.all


I have a promise, aPromise that calls a server, and a non-promise, notAPromise which is called synchrously, that I need to both call and then do something with the results. I have this but not sure if it is the best thing to do

Promise.all([aPromise(), Promise.method(notAPromise)()])
.spread(function(result1, result2) {
    //do something with results
})
.catch(function(error) {
    //do something with error
});

Is it right to put the synchronous notAPromise in the Promise.all or should it be outside?

The benefit of this way is, if aPromise takes a while returning from a server notAPromise will have finished by the time it is back. Or the other way, we wouldn't have to wait until the synchronous notAPromise had finished before calling the server.

Is there a better way I should be writing this code?

EDIT: Also rather than returning a result, if notAPromise was changing some state but I only wanted that new state if aPromise returned successfully too could there be a problem. if aPromise throws but notAPromise has completed we would be in the new state wouldn't we?


Solution

  • Your code is absolutely fine (and even handles the case that notAPromise will throw). However, usually one would simple write

    aPromise().then(function(result1) {
        var result2 = notAPromise();
        //do something with results
    }).…
    

    when we don't care in what order or at what time the two functions are called. It is expected that the synchronous notAPromise takes an unremarkable amount of execution time, if it would matter (and should be able to run in parallel with something else) it should've been asynchronous.