循环中 异步变成同步

// 1、递归
const arr = 'abcdefg'.split('')
const it = arr[Symbol.iterator] ()
setTimeout(function loop () {
    let i = it.next()
    if (i.done) return 
    console.log(i.value)
    setTimeout(loop, 1000)
}, 1000)

// 2、await
const arr = 'abcdefg'.split('')
function sleep(time) {
  return  new Promise(resolve => {
    setTimeout(resolve, time)
  })
}

async function  main (arr) {
  for (let i of arr) {
    await sleep(1000)
    console.log(i)
   }
}

main(arr)

 

posted @ 2017-06-07 09:14  创业男生  阅读(553)  评论(0编辑  收藏  举报