1

So lets say you have this sync function you call a and another async function b that you want to put within a. And so you would have something like this:

async function b(){
      //some code here
}
function a(){
    

}

And now lets say we add some code into a and call b:

async function b(){
      //some code here
}
function a(){
      b()
      //other code here
}

Now lets say you want to run the code within a only if b has returned its promise. Well if you have direct access to b then its all fine, just make it a sync function. That would work but what if you didn't have access to b. Here comes the problem. If you specifically want to run it after b then you could use something like .then():

async function b(){
     //some code here
}
function a(){
     b().then(<results for example>=>{
     //other code
     })
}

But what if a was an async function, how would that work? Could i use await or anything of that sort?

8
  • 4
    Pretty much the only reason to have async functions is to use await inside them. There is almost no benefit if you don't. Commented Apr 28, 2022 at 14:03
  • how would that work tho? Commented Apr 28, 2022 at 14:03
  • @VLAZ The other benefit is that exceptions and return values are converted into promises Commented Apr 28, 2022 at 14:04
  • @JuanMendes it's part of the "almost". It's a very small benefit. I'd say await is more than 90% of the reason to use async. Commented Apr 28, 2022 at 14:07
  • 6
    @DcraftBg — You should probably start out with the MDN documentation for language features you don't understand in order to get a basic understanding of them before resorting to SO. Commented Apr 28, 2022 at 14:08

1 Answer 1

3

You have to make a function async and await for b function, then b function will return data, otherwise it will return promise.

async function b(){
    //some code here
}
async function a(){
    const data = await b();
    // Do something with data
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.