Async and await

Talking about Async/Await
Handling asynchronous with async/await

Async and await

async: Declare an asynchronous function (async function someName(){...})

  • Automatically convert regular functions intoPromise, the return value is also aPromiseObject
  • onlyasyncThe asynchronous operation inside the function is executed before it is executed.thenThe callback function specified by the method;
  • Asynchronous functions can be used internallyawait

await: suspending asynchronous function execution (var result = await someAsyncCall())

  • Place inPromiseBefore calling,awaitForce other code to wait untilPromiseComplete and return the result;
  • Only withPromiseUsed together, not for use with callbacks;
  • Only inasyncThe function is used internally.
Await fault tolerance
  • awaitThe back needs to be aPromiseObject, if not, will be converted intoPromiseObject
  • As long as one of them ifPromiseObject becomesrejectState, then the wholeasyncThe function will interrupt the operation;
  • If the status isresolve, then the return value will becomethenThe parameters inside.
async  function f() {
    return await 123
}
f().then(v => { 
    console.log(v) // 123
})

How to be fault tolerant? due toawaitBackpromiseThe result of the operation may berejectedBest to putawaitput into atry {} catch {}in.

awaitAfter the asynchronous operation, if there is no dependency on each other, it is best to trigger at the same time, which will be introduced in the following scenario.

awaitOnly inasyncAmong the functions, if you are in a normal function, an error will be reported.

Async, await advantages and disadvantages
  • async with awaitCompared to direct usePromiseThe advantage is thatthenThe call chain can write the code more clearly and accurately;
  • The disadvantage is abuseawaitMay cause performance problems becauseawaitWill block the code, maybe the subsequent asynchronous code does not depend on the former, but still need to wait for the former to complete, causing the code to lose concurrency.
var a = 0
var b = async () => {
  a = a + await 10
  console.log('2', a) // -> '2' 10
  a = (await 10) + a
  console.log('3', a) // -> '3' 20
}
b()
a++
console.log('1', a) // -> '1' 1
  • First functionbExecute first, after executionawait 10Previous variablea still is0,Becauseawait Internally implementedgeneratorsgenerators Will keep things in the stack, so this timea = 0Was saved
  • becauseawait Is asynchronous operation, encounteredawaitWill return immediatelypendingStatefulPromiseThe object temporarily returns control of the execution code, so that the code outside the function can continue to execute, so it will be executed first.console.log('1', a)
  • At this time, the synchronization code is executed, start executing the asynchronous code, and use the saved value for use.a = 10
  • Then there is the regular execution code.
scene one

Write a function and let it returnpromiseObject, the function of this function is2sThen multiply the value by2

// returns double the value after 2s
function doubleAfter2seconds(num) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(2 * num)
        }, 2000)
    } )
}

Write another nowasyncFunction so that it can be usedawaitKeyword,awaitPlaced behind is returningpromiseAn expression of the object, so it can be written laterdoubleAfter2seconds The call to the function.

async function testResult() {
    let result = await doubleAfter2seconds(30)
    console.log(result)
}
 testResult() // Open the console. After 2s, the output is 60.

Specific to our code, encounteredawaitAfter that, the code is suspended and waitingdoubleAfter2seconds(30)Finished,doubleAfter2seconds(30)returnpromiseStart execution, after 2 seconds,promisecarried outresolve And returned a value60At this timeawaitOnly get the return value60And then assign it toresult, the pause ends, the code begins to execute, executeconsole.logStatement.

Scene two

We also issue three requests that are not dependent on each other, ifasync/awaitIt seems unwise.

async function getABC() {
  let a = await getA() {}
  let b = await getB() {}
  let c = await getC() {}
  return A*B*C
}

Above we need 2s, B needs 4s, C needs 4s, C needs 3s, we send requests as shown above, there is a relationship of mutual dependence, c, etc. b is executed, b, etc. is executed, starting from the beginning to the end (2+3 +4) = 9s.
At this point we need to usePromise.all()Asynchronous calls are executed in parallel, rather than one after another, as follows:

async function getABC() {
  let results = await Promise.all([ getValueA, getValueB, getValueC])
  return results.reduce((total, value) => total * value)
}

This will save us a lot of time, from the original 9s to 4s, is not very happy, yeah~

Intelligent Recommendation

Database SQL combat 1: Find all the information of the latest employees

thought: The topic asks to find all the information of the latest employees. Through a sub-query (select max(hire_date) from employees), find the latest hire time of the employee, hire_date, and then ...

Correction of TOPSIS model based on entropy weight method

Recently, I am learning mathematical modeling and found a very good course on B station. It is very comprehensive and all the algorithms I often test involve:Qingfeng Mathematical Modeling This articl...

51nod longest common subsequence output path +

When x = 0 or y = 0 when f [x] [y] = 0 When a [x] = b [y] when f [x] [y] = f [x-1] [y-1] +1 When a [x]! = B [y] when f [x] [y] = max (f [x] [y-1], f [x-1] [y]) Note that the string 1 from the start, b...

Enumeration algorithm summary

I learned the enumeration algorithm in this section. The enumeration method is the nature of the problem itself, and all possible solutions are listed in one by one, and in the process of listed one b...

More Recommendation

Two value methods for Map of Java brushing knowledge points: keySet and entrySet, HashMap, Hashtable, TreeMap, LinkedHashMap, ConcurrentHashMap, Weak...

  The interface java.util.Map includes three implementation classes: HashMap, Hashtable, and TreeMap. Of course there are LinkedHashMap, ConcurrentHashMap, WeakHashMap.   Map is used to storeKey-value...

Everyday fresh items

Everyday fresh items - project preference Understand the e-commerce Web project development process Project demand analysis Page page Function map Deployment page Project framework Understand the e-co...

The easiest way: install opencv on windows platform python, that is to achieve import cv2 function

The following old method used before installed opencv, after reinstalling the system, reinstalled opencv according to the original method, and the result has always been reported: ImportError: Module ...

Matlab programming skills: reading and writing text files

Various text files are involved in MBD (model-based design), and the automated processing of text files can greatly improve work efficiency. This article briefly introduces the first step of processin...

Mysql opens a remote connection

1. Log in to Mysql cmd enter mysql -u root -pyoupassword (Input rule After you press Enter, you will be prompted to enter the password. Note that there may or may not be spaces before the user name, b...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top