Since you've given us no real code and no specific information on your APIs, I will offer an answer assuming that the APIs return promises or can be made to return promises. In that case, sequencing and doing error handling is quite simple:
ascync function main() {
let step1Result = await step1();
let step2Result = await step2();
let step3Result = await step3();
return finalValue;
}
// usage
main().then(finalResult => {
console.log(finalResult);
}).catch(err => {
console.log(err);
});
Some things to know:
- Because
main
is declared async
, it can use await
internal to its implementation.
- Because
main
is delcared async
, it will always return a promise
- This code assumes that
step1()
, step2()
and step3()
return promises that are linked to the completion or error of one or more asynchronous operations.
- When the function is executing, as soon as it hits the first
await
, the function will return an unresolved promise back to the caller.
- If any of the
await stepX()
calls reject (e.g. have an error), that will abort further execution of the function and reject the promise that was previously returned with that specific error. It works analogous to throw err
in synchronous programming, but the throw is caught automatically by the async
function and turned into a reject for the promise that it already returned.
- Your final return value in the function is not actually what is returned because remember, a promise was already returned from the function when it hit the first
await
. Instead, the value you return becomes the resolved value of that promise that was already returned.
- If your API interfaces don't currently return promises, then you can usually find a wrapper that someone has done to create a version that will return promises (since promises are the modern way of working with asynchronous interfaces in Javascript). Or, you can create your own wrapper. In node.js, you can use
util.promisify()
or you can manually make your own wrapper (just takes a few lines of code).
- If you need to catch an error within the function in order to handle it and continue, you can either wrap a given
await
call in try/catch
or use .catch()
on the promise and "handle" the error and continue processing, again similar to handling exceptions in synchronous code.
If any of the steps had an error and rejected their promise, then main()
will abort and reject similar to throwing an exception in synchronous code.
See also:
How to chain and share prior results with Promises