Search code examples
javascriptnode.jsasynchronousasync-awaitnode-fetch

When does the async / await chaining stop?


I was testing node-fetch and when I was using async / await, a question came up : I have to make my function async if I use await in it BUT since my function is async I need to await it and make the parent function async. And so on... Context :

async functionA()
{
  var result = await functionB();
}

async functionB()
{
  //do things
  var result = await functionC();

  //do things

  var blob;

  //do things

  return blop;
}

async functionC()
{
 //here is the real async call
 var result = await fetch(....);
 var json = await result.json();
 return json;
}

}

How can I make this async / await chaining stop ? I have one method in my program using fetch and it will make me transform all my others methods to async method. Is this really how all others program developped with fetch look like ? Perhaps I didn't understand something with async/ await.

Thanks for your time :)


Solution

  • Call the asynchronous function once, at the beginning of your script. After its response comes back, call the rest of your script with the result synchronously. Something along the lines of:

    async function functionC() {
     //here is the real async call
     const response = await fetch(....);
     const result = await result.json();
     return result;
    }
    
    functionC()
      .then((results) => {
        // do stuff with results
        functionA(results);
        functionB(results); // if needed
        // etc
      })
      .catch(handleErrors); // don't forget this part
    

    This way, only one part of your script - near the entry point - needs to handle the asynchronous logic. Implementing this may well require some refactoring, but it's worth it over the alternative of making everything async.

    (also note that .json resolves to a plain object or array, probably - it doesn't resolve to a string in JSON format, it parses the Response stream as if it was JSON and resolves to the result, which is no longer a JSON-formatted string, but a plain value, usually an object or array)