js 异步for轮回

假定一位厨师,须要做3道菜,声明一个菜数组,菜对象是菜名和做菜须要的时候

let dishes=[{name:"fish",time:1},{name:"fish1",time:2},{name:"fish3",time:3}]

起首,厨师做菜应当一道接一道的做,所以得保证一道菜做后才最先做下一道菜。这里用async/await完成,固然也能够挑选都用Promise

    (async ()=>{
      for (let d of ds) {
          console.log("最先做"+d.name)
          await (() => {
            return new Promise(res => {
              setTimeout(res, d.time * 1000)
            })
          })();
          console.log("做好了"+d.name)
        }
    })
    原文作者:ZoeLee
    原文地址: https://segmentfault.com/a/1190000015565421
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞