Reputation: 29
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);
});
}
Upvotes: 0
Views: 68
Reputation: 1794
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.
Upvotes: 0
Reputation: 29
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.
Upvotes: 2