When an asynchronous action is performed, if you want to wait for its success or failure and avoid several chains of callbacks. See callback hell.
- I identified the asynchronous call I want to wait for
- I included the function into a callback, the executor of the Promise will handle an asynchronous work (in the examples below the describeTable). Once the work is done, if it went well, we are calling the resolve function, if not we are calling the reject one.
export const waitForCallbackToBeSolved = () => {
asynchronousAction(params, (error, data) => {
// We create a Promise with the function using a callback in second arguments
if (error) throw error;
else console.log(data);
});
};
export const getResponse = async () => {
try {
await waitForCallbackToBeSolved();
doStuff();
} catch (error) {
log(error);
throw error;
}
};
-> [ ] Neither Promise
nor promisify
had been used hence we are sending a 200 status in all cases
export const waitForCallbackToBeSolved = () => {
return new Promise((resolve, reject) => {
// We create a Promise with the function using a callback in second argument
asynchronousAction(params, (error, data) => {
if (error) {
return reject(error);
}
resolve(data);
});
});
};
export const getResponse = async () => {
try {
await waitForCallbackToBeSolved();
doStuff();
} catch (error) {
log(error);
throw error;
}
};