async await 配合 promise使用,代码更加简洁

923 阅读1分钟
const promise = (data) => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(data)
    }, 2000)
  })
}

const test = async () => {
  console.log(1, new Date())
  const value1 = await promise(5);
  console.log(2, value1, new Date());
  const value2 = await promise(6);
  console.log(3, value2, new Date())
}

test()

可以看到运行结果:

1 2020-05-24T02:22:14.509Z
2 5 2020-05-24T02:22:16.517Z
3 6 2020-05-24T02:22:18.522Z