The ES7 async and await

async 和 await

If you add a function async, then the function returns a Promise

async function test() {
  return "1"
}
console.log(test()) 
// -> Promise {<resolved>: "1"}

async is the return value of the function Promise.resolve () wrapped next, and then the process returns to the same value, and only supporting async await use.

async function test() {
  let value = await sleep()
}

async and await an asynchronous can be said that the ultimate solution, compared to the direct use of Promise, the advantage of processing the call chain then can be more clearly and accurately write code, after all, write a lot of then very sick, and can also callback hell elegant solution to the problem.

Of course, there are some drawbacks, since await the asynchronous code is transformed into synchronization code , if multiple asynchronous code but is not dependent on the use of reduced performance will lead to await.

async function test() {
  // 以下代码没有依赖性的话,完全可以使用 Promise.all 的方式
  // 如果有依赖性的话,其实就是解决回调地狱的例子了
  await fetch(url)
  await fetch(url1)
  await fetch(url2)
}

Await a look at an example using:

let a = 0
let b = async () => {
  a = a + await 10
  console.log('2', a)
}
b()
a++
console.log('1', a)

//先输出  ‘1’, 1
//在输出  ‘2’, 10
  • First function b executed first, to await execution in 10 before a variable or a zero, because the internal await achieve a generator, generator will keep the stack of things, so that when a = 0 is preserved
  • Because await asynchronous operation, then the expression does not return Promise, it would packaged Promise.reslove (return value), and then to perform the synchronization code will be a function of the outer
  • Synchronization code performs a print with a ++ After completion of the start value asynchronous code, put to use the saved, this time a = 0 + 10

The above mentioned internal await explanation achieve a generator, in fact, await generator is coupled with syntactic sugar Promise, and the internal implementation of the automatic execution generator .

Code analysis problem

function wait() {
  return new Promise(resolve =>
    setTimeout(resolve,  1000)
  )
}

async function main() {
  console.time();
  const x = wait();
  const y = wait();
  const z = wait();
  await x;
  await y;
  await z;
  console.timeEnd();
}
main();

Answer: Output time: a little more than a second.
The reason: 3 wait function when the assignment had already started to be implemented.

Slightly modified what you can get more than 3 * 1000 ms results

function wait () {
  return new Promise(
    resolve => setTimeout(resolve,  1000)
  )
}

async function main () {
  console.time()
  const x = await wait()
  const y = await wait()
  const z = await wait()
  console.timeEnd()
}

main()

Guess you like

Origin www.cnblogs.com/nayek/p/11728872.html