Async/await ECMAScript 6

This functionality is not introduced by ECMAScript 2015 but by ECMAScript 2017, and for use await, your function must be marked as async. When you use the keyword await before a promise, you pause the execution of the async function, wait for the resolution of the promise, and then resume the execution of the async function. The value returned is the value resolved by the promise.

So we can write our previous example using async / await like this:

async function getUserRightsAndUpdateMenu() {
// getUser is a promise
const user = await getUser(login);
// getRights is a promise const rights = await getRights(user);
updateMenu(rights);
} await getUserRightsAndUpdateMenu();

And our code looks completely synchronous! Another pretty cool feature of async / await is the ability to use a simple try/catch to handle errors:

async function getUserRightsAndUpdateMenu() {
try {
// getUser is a promise
const user = await getUser(login);
// getRights is a promise
const rights = await getRights(user);
updateMenu(rights);
} catch (e) {
// will be called if getUser, getRights or updateMenu fails
console.log(e);
} } await getUserRightsAndUpdateMenu();

Note that even though the code looks like synchronous code, it remains asynchronous. The execution of function is paused and resumed, but, as with callbacks, it does not block the thread Execution: Other events can be managed while the execution is paused.

we provide professional ES6 / Javascript Job Support to all over the world. No matter you are a student, aspirant, fresher, or even a professional, we will not only provide Job Support to you, we will resolve all issues regarding Python but will also provide you enough training to deal with all kinds of difficult tasks that may come in this particular area of work.

Comments