Sunday, 2 April 2017

Conditional call to second async function, based on data collected before the first async function

I have some data in a array.

let data = ['firstData', 'secondData'];

The first object (firstData) always exists, secondData could be null. So I always use that to call my async function like:

myAsyncFunction(data[0]).then(result => {
    //do something here
});

If data[1] exists, I wanna call myAsyncFunction with data[1].

My current solution is with nested promises. Like this:

myAsyncFunction(data[0]).then(result => {
    return result;
}).then(result => {
    if(data[1] !== null){
        myAsyncFunction(data[1].then(resultTwo => {
        //dostuff with data
      });
    }
});

I don't really like this solution, but it does work. It must be a better way tho. result is always a object. I tried Promise.all but it does not work. I think it's a problem with "race condition" of some sort (I am on thin ice here).

Is my current solution the only one?



via mintermasher

No comments:

Post a Comment