async和await

理解了promis语法,我们就可以来学习async和await关键字,它们是ES2017的新特性,简单点说就是promise语法的语法糖,目的就是为了让代码看起来更像同步代码,进一步增加了代码的可读性。

这两个关键字都是一起使用。我们来写一个只用promise语法写的代码:

const p = new Promise(resolve => {
  resolve("hell")
})
p.then(ret => {
  console.log(`${ret}o`) // hello
  return ret
})
.then(ret => {
  console.log(`${ret} world`) // hello world
})

promise特有的链式调用,现在用async和await来改写,去掉then方法。固定使用:async只能用在函数定义之前,await只能用在async函数内。

function retPromise() {
  return new Promise(resolve => {
    resolve("hell")
  })
}
async function hello() {
  const hell = await `hell`
  const hello = `${hell}o`
  console.log(hello)
}
hello()

捕获error可以使用try...catch...

 

posted @ 2020-12-12 11:00  xqcokid  阅读(35)  评论(0编辑  收藏  举报