zoukankan      html  css  js  c++  java
  • 一种通过async/await实现函数同步执行的方式

     1 const testArr = [
     2   () => {
     3     return new Promise((resolve, reject) => {
     4       setTimeout(()=> {
     5         alert(1);
     6         resolve();
     7       }, 300);
     8     });
     9   },
    10   () => {
    11     return new Promise((resolve, reject) => {
    12       setTimeout(()=> {
    13         alert(2);
    14         resolve();
    15       }, 500);
    16     });
    17   },
    18   () => {
    19     return new Promise((resolve, reject) => {
    20       setTimeout(()=> {
    21         alert(3);
    22         resolve();
    23       }, 100);
    24     });
    25   }
    26 ];
    27 
    28 async function iterate(arr) {
    29   let index = 0;
    30   while (index < arr.length - 1) {
    31     await arr[index]();
    32     index += 1;
    33   }
    34   return arr[index]();
    35 }
    36 
    37 iterate(testArr);

    建议在https://codepen.io/pen上执行查看,挂载https://cdn.bootcss.com/babel-polyfill/7.0.0-alpha.12/polyfill.js

    若您嫌麻烦,直接点这里: https://codepen.io/timrchen/pen/NggaEj

  • 相关阅读:
    第四章5
    第四章4
    第四章3
    第四章2
    第四章1
    第四章例4-8
    第四章例4-7
    第四章例4-6
    第四章例4-5
    第四章例4-4
  • 原文地址:https://www.cnblogs.com/tim100/p/7065406.html
Copyright © 2011-2022 走看看