Q.Promise array, alert if more than 1 is executed

I am using the Q library to handle promises. Suppose I have an array of promises, which I wait for the first to be executed to return its value.

I expect that only one of the promises will be fulfilled, but I cannot guarantee this situation, and therefore I would like to do SOMETHING if another promise is fulfilled after the first.

Obviously, I could use Q.allSettled, but then I would have to wait for all the promises to be fulfilled / rejected before I could access the value of the first promise made.

I was wondering if there is a way to access the value of the first promise, which will be returned, but still handle other promises, so I can warn if another promise, if it is fulfilled.

Hope my question is clear, thanks for your help.

Edit1 - code snippet

As you can see, this code returns the value of the first promise made. I want to keep this behavior while I can still act if the 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);
});

Edit2 - additional information

Given that you understand what the above code should do, I have a generic function GetDataSource(profileId): Q.Promise<DataSource>( input: profileId, output: a promise for a DataSource).

, , --- Q.any(promises). , (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
    }
});

? ( , )

+4
1

fork promises :

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
    }
});
+2

Source: https://habr.com/ru/post/1619710/


All Articles