0

Im new to programming and am confused about the async function present in the javascript language. Why do you use it, and how?

Short demo:

function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved');
    }, 2000);
  });
}

2 Answers 2

2

An async function is a function declared with the async keyword. Async functions are instances of the AsyncFunction constructor, and the await keyword is permitted within them. The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains.

Sign up to request clarification or add additional context in comments.

Comments

0

If we start from first principles, it will be helpful to understand what "asynchronous" means:

https://developer.mozilla.org/en-US/docs/Glossary/asynchronous

Asynchronous software design expands upon the concept by building code that allows a program to ask that a task be performed alongside the original task (or tasks), without stopping to wait for the task to complete.

And have a good understanding of the different approaches to handle asynchronicity like callbacks functions and promises.

If you have those, @Jeffrey's answer is a solid explanation of what the async-await syntax is – a nicer way to express what promises do. For further reading you can see Making asynchronous programming easier with async and await.

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.