Photo by RetroSupply on Unsplash
JavaScript 2022 - New Features - Part 4
ECMAScript 2022(ES13) : New Capabilities
Table of contents
Top level await operator
The await operator was added in ES8(ECMAScript 2018) it pauses the execution until a promise is completed or rejected.
With ES13 the await operator can be used in global scope.
// await with function - toplevel
// Awaiting a promise to be fulfilled
function resolveAfter2Seconds(x) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(x);
}, 1000);
});
}
await resolveAfter2Seconds(10).then(
arg => {console.log("then",arg);}
);
In the above code the await operator is used
With a standard function (non async)
In a global context
When the function's promise is completed the then() function is called which prints the value 10.
The await operator can also be used for loading modules
//mymath.mjs
export function add(a,b) {
return a+b;
}
// program.js
let module;
try {
module = await import('./mymath.mjs');
console.log("Module loaded", module);
} catch {
console.log("error")
}
In the above code module mymath.mjs is loaded using await keyword