Shopware Silver & extension partner
Certified Advanced Developers & solution architects
200+ E-commerce Rrojects
50+ Professional developers
The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style.
An async function is a function declared with the async keyword, and the await keyword is permitted within it. 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. async/await builds on top of promises: an async function always returns a promise. await “unwraps” a promise and either results in the value the promise was resolved with, or throws an error if the promise was rejected.
We need to use them because they allow you to write promise-based code as if it were synchronous, but without blocking the main thread. They make your asynchronous code less “clever” and more readable.
async function firstAsyncFunction() {
try {
const fulfilledValue = await promise;
}
catch (rejectedValue) {
// …
}
}
If you use the async keyword before a function definition, you can then use await within the function. When you await a promise, the function is paused in a non-blocking way until the promise settles. If the promise is fulfilled, you get the value back. If the promise rejects, the rejected value is thrown.
async function callAsyncFunction(name){
return new Promise((resolve, reject) => {
resolve(`My name is ${name}`)
})
}
async function getName(name){
const result = await callAsyncFunction(name);
return result;
}
(async () => {
console.log(await getName('Blerona Idrizi'))
})()
The result wil be: My name is Blerona Idrizi