DEV Community

Discussion on: JavaScript Awaits

Collapse
 
godspeedelbow profile image
Eelke Boezeman

It happens often that an asynchronous function takes more than one (earlier computed) asynchronous value. With async/await, all the async function calls are done within the same function scope, exposing the values within that scope, and therefore composing those values with other asynchronous functions requires much less boiler plate.

async function f() {
    const dataString = await getServerData();
    const parsedData = await parseData(dataString);
    const filteredData = await filterData(parsedData, dataString); // <-- scoped access to dataString
}
Enter fullscreen mode Exit fullscreen mode

Using a promises-only approach, or callbacks only, or something like the async library will always result in a lot more boiler plate to have access to dataString, e.g. promises-only:

function f() {
  getServerData()
  .then(dataString => [dataString, parseData(dataString)]), // <-- pass dataString along
  .then([dataString, parsedData] => filterData(parsedData, dataString)) // <-- so you can access it here
}
Enter fullscreen mode Exit fullscreen mode