Home > Software design >  Async/await pausing concept
Async/await pausing concept

Time:08-01

Let's say we have two Async functions:

function someOtherAsyncFunc() {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve()
            }, 3000)
        }) 
}


async function asyncFunc() {
    const asyncData =  await someOtherAsyncFunc()
    console.log("sync task that doesn't depend on the asynchronous data")
    asyncData.doSomething()
}

Is there a way not to pause the function execution until only the asynchronous variable is referenced later on in the code?

  • Get the asynchronous data asynchronously
  • Continue the execution until that data is needed and then 'await' it

CodePudding user response:

Sure, just declare the Promise alone without extracting the value from it - only extract the value from it once you actually need it.

async function asyncFunc() {
    const asyncDataPromise = someOtherAsyncFunc()
      // .catch(handleErrors)
      // catching would be nice to see here, though probably not strictly necessary
      // if the rest of the code is completely synchronous and won't return before awaiting
    console.log("sync task that doesn't depend on the asynchronous data")
    (await asyncDataPromise).doSomething()
}

But if the other code in question is synchronous, it would often make more sense from a code organization perspective to only make the async request once you want to wait for it.

async function asyncFunc() {
    console.log("sync task that doesn't depend on the asynchronous data")
    const asyncData =  await someOtherAsyncFunc()
    asyncData.doSomething()
}
  • Related