[Front-end Basics] Talk about asynchronous functions Async and await

Look at two simple asynchronous function questions

async function foo() {
    
    
  console.log(2);
  console.log(await Promise.resolve(8));
  console.log(9);
}

async function bar() {
    
    
  console.log(4);
  console.log(await 6);
  console.log(7);
}

console.log(1);
foo();
console.log(3);
bar();
console.log(5);

The printing order here is: 1 2 3 4 5 8 9 6 7; the explanation is: the first two are declaring functions, the latter executes printing 1, and then executes the foo function to print 2. When encountering await, the execution is suspended and the subsequent tasks are put in in the asynchronous queue and provide the agreed-upon value to the asynchronous task. Then print 3 and 4, and when encountering await, the execution will be suspended, and the immediately available 6 will be added to the asynchronous message queue for subsequent tasks. Print 5, print 8, print 9, print 6, print 7.另一种答案是因为await做过修改,所以新版的浏览器是上面的结果,修改为await Promise.resolve(8)立即解决8,然后把本行代码和后面的代码放入异步任务中。

For actual development, we usually pay more attention to the results of parallel asynchronous operations rather than relying on the execution order.

For example variant:

async function foo() {
    
    
  console.log(2);
  console.log(await Promise.resolve(8));
  console.log(9);
  return 6;
}

async function bar() {
    
    
  console.log(4);
  console.log(await foo());
  console.log(7);
}

console.log(1);
foo();
console.log(3);
bar();
console.log(5);

The printed result is: 1 2 3 4 2 5 8 9 8 9 6 7.
If you don’t understand, you can leave a comment or send a private message, and I will definitely reply.

Asynchronous functions can implement sleep()

//非阻塞的暂停
async function sleep(delay) {
    
    
  return new Promise((resolve, reject) => {
    
    
    setTimeout(resolve, delay, 1);
  });
}

async function foo() {
    
    
  console.time("w");
  await sleep(3000); //这个后面的代码是异步的。
  console.timeEnd("w");
}
foo();
//w: 3.002s

Guess you like

Origin blog.csdn.net/qq_42146383/article/details/123374855