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?
Here is what myAsuncFunction looks like:
myAsyncFunction(personData){
return new Promise<any> ((resolve, reject) => {
//Assingen private variables
secondAsyncFunction(somePersonData).then(result =>
{
//Do some sync stuff
return someNewData; //not a promise
})
.then(thirdAsyncFunction)
.then(data => {
resolve(data);
})
.catch(error => {
reject(error);
});
});