Tetegw
4/8/2018 - 9:04 AM

await/async

es7 await/async

let sleep = function (timeout) {
  return new Promise(function (resolve, reject) {
    setTimeout(function () {
      resolve(`sleep ${timeout}`)
    }, timeout)
  })
}

/* sleep(3000).then((res) => {
  console.log(res)
}).catch((res) => {
  console.log(res)
})  */

let start = async function(timeout) {
  try {
    console.log('start')
    for (let i = 0; i < 10; i++) {
      // 注意这里不能用forEach,会改变上下文,await必须在async的上下文中
      let res = await sleep(timeout)
      console.log(`次数${i}---${res}`)
    }
    console.log('end')
  } catch (error) {
    // async 需要catch错误
    console.log(error)
  }
}
start(1000)

// Promise对象减少了深层嵌套问题,但是未解决异步的写法(.then)
// async和await配合Promise对象,解决了异步的写法