I'm working on an app where I need to make an API call which is in a function then use its value to make another API call. But the first API call's value is not readily available as it depends on some external factors. So after making the first API call I need to make 3 API calls in 5 second intervals to check if the value is available or not. If it is then make the second API call else don't make the second API call.
Now I know I have to do this Promises and I tried doing it but I'm not sure if what I'm doing is right.
This is what I could do about the Promise function:
const promiseFunc = ( param1, param2 ) => {
return new Promise(( resolve, reject ) => {
const func1 = api1( param1 );
if ( func1.code === '200' ) {
const startInterval = setInterval( () => {
const check = getValue();
if ( check && check === param2 ) {
clearInterval( startInterval );
resolve();
} else {
reject();
}
}, 5000);
} else {
reject();
}
});
}
So what is happening in the above func is that it takes two parameters for calling the api calls.
func1 is executed and if it returns 200 then start the interval timer. Please note that api1 function call is the API call. I tried using await there but it throws error. And I'm not sure if I can use async/await inside a Promise function.
Moving on, check variable starts making api calls (getValue() is also a function which includes the api endpoints) to check the value if it is available or not. if it is then resolve, if it doesn't then reject.
Here's how I'm executing the promiseFunc in sequence:
promiseFunc( myChosenValue1, myChosenValue2 )
.then( data => {
return promiseFunc( valueFromFirstExecution1, valueFromFirstExecution2 )
})
.then( () => {
console.log( 'Successfully executed both the functions' );
})
.catch( e => {
console.log( e );
});
This is the farthest I could go in writing a Promise function and I know there are multiple issues in the above code. The first function gets executed properly but then I get this error TypeError: Cannot read property 'code' of undefined. Also, I'm not sure if the API calls in setInterval would run. Any thoughts?