Experience with async/await

Running Environment This method is supported above node7 This feature is supported above chrome55 and is typically used...

Running Environment

This method is supported above node7
This feature is supported above chrome55 and is typically used in node development

Introduction to async

Async is actually the syntax sugar of promise, a method marked by async that returns a promise object
async is defined as follows:

async function name([param[, param[, ... param]]]) { statements }

Return to AsyncFunction as a promise instance
When the async function returns a value, Promise's resolve method handles the value; when the async function throws an exception, Promise's reject method handles the exception.

Introduction to await

await generally needs to be used with async tagged functions
The await expression pauses the execution of the current async function and waits for the Promise process to complete.
The value returned by the await tag's method call is actually the value returned by promise's resolve method
If Promise processes normally (fulfilled), the result of its processing continues to execute the async function as the value of the await expression.
If Promise handles rejected exceptions, the await expression throws the cause of Promise's exceptions.
In addition, if the value of the expression after the await operator is not a Promise, the value will be converted to a properly processed Promise.

Official Document Cases

Normal operation
function resolveAfter2Seconds(x) { return new Promise(resolve => { setTimeout(() => { resolve(x); }, 2000); }); } async function add1(x) { var a = resolveAfter2Seconds(20); var b = resolveAfter2Seconds(30); return x + await a + await b; } add1(10).then(v => { console.log(v); // prints 60 after 2 seconds. }); async function add2(x) { var a = await resolveAfter2Seconds(20); var b = await resolveAfter2Seconds(30); return x + a + b; } add2(10).then(v => { console.log(v); // prints 60 after 4 seconds. });
Exceptional circumstances
async function f3() { try { //If the reject method of promise is called, it will be caught by an exception var z = await Promise.reject(30); } catch (e) { console.log(e); // 30 } } f3();

Today I wrote an interface that mimics websocket s, which is used in the code to look directly at the source code

//websocket listens for messages ws.on('message', async function (message) { //Note that the async tag is used on the anonymous function, otherwise an error is reported var stockRequest = JSON.parse(message);//Update according to the requested data. console.log("Received Message", stockRequest); let result = await startSendMessage(); }); /** * send message */ async function startSendMessage(){ for(let i=0,leni=PROVINCE_ARRAY.length;i<leni;i++){ for(let j=0,lenj=RESOURCE_ARRAY.length;j<lenj;j++){ var obj={} wsInstance.send(JSON.stringify(obj)); await sendResult(obj); } } return true } /** * Send results * @param Result Sent */ function sendResult(obj){ let timeStep=randomInterval(1000,4000); return new Promise(resolve => { setTimeout(() => { obj['result'] = getResult(); wsInstance.send(JSON.stringify(obj)); resolve("OK"); }, timeStep); }); }

Reference material
Understanding JavaScript's async/await
MDN async tag description
MDN await tag description

12 July 2020, 11:15 | Views: 6940

Add new comment

For adding a comment, please log in
or create account

0 comments