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?
So you have a couple of things going on here:
So lets write some helpers:
// We need a way to wait for some amount of time before
// retrying a request, sleep sleeps for n milliseconds
const sleep = (n) => new Promise(res => setTimeout(res, n));
// We need a unique sentinel value so we know when we have actual
// results from an API call instead of this default value
const sentinel = {}; // or Symbol, whatever unique you prefer
// poll will take the data necessary to make a fetch
// request and repeat it every `interval` milliseconds
// up to `maxRetries` until it gets a result
const poll = async (url, fetchOpts, interval, maxRetries) => {
let result = sentinel; // default value
let ticker = 0; // current number of retries
while (result === sentinel && ticker < maxRetries) {
// make the api call
const resp = await fetch(url, fetchOpts);
const data = await resp.json();
// do we have a result?
if (isDone(data)) { // whatever criteria == completion
result = data; // breaks the loop
} else {
// wait `interval` milliseconds and try again.
ticker++;
await sleep(interval);
}
}
// Oops! We didn't get an answer back from the
// api in time
if (result === sentinel) {
throw new Error('Exceeded maxRetries!');
}
return result;
};
So now we can actually do the thing we want:
// call this with the eventual result, *if* we
// get one
const onSuccess = (result) => {...}; // whatever
// This is doing the actual work
const doTheThing = async () => {
await fetch(firstApiCall); // kick off the process
try {
// wait for completion
const data = await poll(url, {}, 5000, 6); // ~30sec timeout
// pass successful result onwards
return onSuccess(data);
} catch (err) {
// Error bubbling is a little weird with async
// functions, so we'll just handle it here and
// return undefined
console.error(err)
return
}
};