Reputation: 5568
I'm using Q library for handling promises. Lets say I have an array of promises, which I'm waiting for the first one to be fulfilled in order to return its value.
I'm expecting only one of the promises to be fulfilled, yet I cannot guarantee this situation and therefore I'd like to do SOMETHING if another promise has been fulfilled after the first one.
Obviously I could use Q.allSettled but then I'd have to wait for all the promises to be fulfilled/rejected before I could access the value of the first fulfilled promise.
I was wondering if there's a way of accessing the value of the first promise to be returned while still handle the other promises, so I can alert if another promise if fulfilled.
Hope my question is clear, thanks for your help.
As you can see, this code returns the value of the first fulfilled promise. I want to keep this behaviour while still being able to take action if a second promise is fulfilled.
var getDataSourcePromise = function(table, profileId) {
var deferred = Q.defer();
table.retrieveEntity(tableName, profileId, profileId, function(err, result, response) {
if (err) {
deferred.reject(Error(err));
}
else {
deferred.resolve(result);
}
});
return deferred.promise;
}
var promises = [];
tables.forEach(function(table, profileId) {
promises.push(getDataSourcePromise(table, profileId.toString()));
});
console.log('waiting for settle');
Q.any(promises).then(function(result) {
console.log(result);
});
Given you understand what the above code should do, I have a generalized GetDataSource(profileId): Q.Promise<DataSource>
function (input: profileId
, output: a promise for a DataSource
).
I need to return the value of the first fulfilled promise to whomever called me, as soon as it was fulfilled --- meaning I need to return Q.any(promises)
.
On the other hand, I still need to execute this part of code (Benjamin Gruenbaum's):
Q.allSettled(promises).then(function(result){
if(result.filter(function(p){ return p.state === "fulfilled"; })){
alert("Sanity failure"); // do whatever you need to recover
}
});
What do you recommend I do? (sorry for not being clear enough before)
Upvotes: 4
Views: 95
Reputation: 276306
You can fork promises and create multiple branches:
var promises = tables.map(function(table) {
return getDataSourcePromise(table, profileId.toString());
});
Q.any(promises).then(function(result){
console.log("Result", result); // processing done
});
Q.allSettled(promises).then(function(result){
if(result.filter(function(p){ return p.state === "fulfilled"; })){
alert("Sanity failure"); // do whatever you need to recover
}
});
Upvotes: 2