The async and await keywords were first introduced in ES7, and the principle behind them is based on generators and promises. Async is called an asynchronous function. It’s new in ES2017 and makes asynchronous operations much easier. It’s essentially the syntax-sugar of a Generator, so it’s still essentially manipulating promise objects to observe the state. Replace the generator and yield in promise methods with a combination of async and await, which is a syntactic sugar.
Of course we can create our own async and await to understand and learn more about these two keywords.
Async and await in ES7
function getServerData(queryParam) { return new Promise((resolve, reject) => { setTimeout(()=>{ resolve({'result': 'querying ' + queryParam + ' is ok!!! '}); }, 100); }); }; async function queryMsg() { try { const data1 = await getServerData('data1'); console.log('query data1: ' + JSON.stringify(data1)); const data2 = await getServerData('data2'); console.log('query data2: ' + JSON.stringify(data2)); } catch (e) { console.log('Error: ', e); } } queryMsg(); console.log('now qeury msg from server');Copy the code
GetServerData A function that gets data asynchronously from the server, returning a promise. The place where the function is called can get the result asynchronously through the method associated with the promise.
If a function is marked async, the call to the function does not block the thread, the function needs to wait for a promise with an await, and the function waiting for an await must return a promise.
The output is as follows:
now qeury msg from server query data1: {"result":"querying data1 is ok!!!" } query data2: {"result":"querying data2 is ok!!!" }Copy the code
Asynchronously Obtaining Data
getServerData('server').then(data=>{
console.log('getServerData: ' + JSON.stringify(data));
}).catch(error=>{});
console.log('first printed');
Copy the code
Since THE introduction of PROMISE in ES6, it has been a lot easier to get data asynchronously. For example, if we want to get data asynchronously from the server, we wait for the result asynchronously and non-blocking using the promise.then method.
Output results:
first printed getServerData: {"result":"querying server is ok!!!" }Copy the code
A generator that does not block
function *generator() { const data1 = yield getServerData('data1'); console.log(data1); // Prints the const data2 = yield getServerData('data2') passed from next(); console.log(data2); }; const gr = generator(); Function handleIteratorResult(result) {if (result.done) {// Return if the generator iteration is complete; } const value = result.value; if (value instanceof Promise) { value.then(res=>{ handleIteratorResult(gr.next(res)); }) } } try { handleIteratorResult(gr.next()); } catch (e) { gr.throw(e); } console.log('now qeury msg from server by generator');Copy the code
Js generator, which has a feature that does not block the current thread while waiting for the return result. A generator whose characteristic is to call next() once and return from the last yield until the next yield, returning the result to the caller. If you pass an argument to next(), that argument will be the value returned from the last yield.
The actual result handled in handleIteratorResult is the promise returned from getServerData, so we can asynchronously wait for the result of the promise and then return it to the generator. The result from the promise passes the result into next(), where the generator gets the result, and then returns the next yield result.
Output results:
now qeury msg from server by generator { result: 'querying data1 is ok!!! ' } { result: 'querying data2 is ok!!! '}Copy the code
Create your own async function
Using the generator above basically implements async and await, we just need to tidy up the program a little more and we’re done:
function async() { const iterator = (function *(){ const data1 = yield getServerData('data1'); console.log(data1); const data2 = yield getServerData('dta2'); console.log(data2); }) (); try { handleIteratorResult(iterator.next()); } catch (e) { gr.throw(e); } function handleIteratorResult(result) {if (result.done) {// Return if the generator iteration is complete; } const value = result.value; if (value instanceof Promise) { value.then(res=>{ handleIteratorResult(iterator.next(res)); }) } } } async(); console.log('now qeury msg from server by my async');Copy the code
The output is as follows:
now qeury msg from server by my async { result: 'querying data1 is ok!!! ' } { result: 'querying data2 is ok!!! '}Copy the code