While I have some basic js coding skills and a few APIs uses in the past, I get stuck with one because it basically contains 3 calls. All async.
Step 1 is pushing a file to the service and get back an ID in return.
Step 2 is requiring a specific operation on the previously pushed file thanks to the ID
Step 3 is downloading the result

The fact is that I need to ensure all of these steps are individually ok before calling the next API endpoint. And exit if something went wrong.
I am having hard times to sequence those three steps.

Eventually, I wish I can manage the 3 steps in one function call as :

function main(){
    //Pseudo code
    calling async step1
    exit if step1 failed
    calling async step2
    exit if step2 failed
    calling async ste3
    exit if step3 failed
    return OK

What I am looking right now is advices on the strategy to tackle this. Right now I am loosing myself in promises/await loops and get crazy.
Thanks in advance for your valuable insights.

The new Async/Await makes super easy to handle this; I am just gonna assume some names and give an example:

/* Fake Functions */

const timeOutPromise = (timeout, returnData) => new Promise(resolve => {
    setTimeout(() => {
    }, timeout);

const fakeFileUpload = () => fetch(
    { method: 'POST' }
).then(response => response.json())

const fakeAjax = (id) => fetch(`https://jsonplaceholder.typicode.com/todos/${id}`)
    .then(response => response.json())

/* Async project functions */
 * @return {{ id: string }}
const uploadFile = async (myFile) => fakeFileUpload(myFile);

 * @return {{ status: string, url: string }}
const processData = async (data) => fakeAjax(data.id)

 * @return {void}
const downloadFile = async (info) => timeOutPromise(500, {status: 'OK', url: 'https://jsonplaceholder.typicode.com/todos/1'})

/* Main Function e.g. Event Handler */
const doAction = async () => {
  const fileInfo = await uploadFile();
  if(!fileInfo) {

  const processedInfo = await processData(fileInfo);
  if(!processedInfo) {

  const downloadInfo = await downloadFile(processedInfo);
  if(!downloadInfo) {
  return downloadInfo;
/* ********** */
/* trigger main Function */

You can see above code block in action here: https://codepen.io/pankajpatel/pen/gObmwmp?editors=0012

I wrote about the recepies of async await here https://time2hack.com/5-code-recipes-asynchronous-code-execution-with-promise-async-await/

let me know if you need some help

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.