美文网首页
ES7 中 async await

ES7 中 async await

作者: Wang_Yong | 来源:发表于2018-02-28 21:56 被阅读0次

处理多个之间相互依赖的请求,使用async和await会更加优雅。
async/await规则一、凡是在前面添加了async的函数在执行后都会自动返回一个Promise对象。
eg:

async function test(){
  
}
let result = test();
console.log(reslut)  // Promise {<resolved>: undefined}

async/await规则二、await必须在async函数中使用,不能单独使用

async function test(){
  let result = await Promise.resolve("sucess")
  console.log(result)
}
test();

async/await规则三、await后面需要跟Promise对象

function fn(){
  return new Promise((resolve,reject)=>{
    setTimeout(()=>{
      resolve("sucess")
    })
  })
}
async function test(){
  let result = await fn();
  console.log(result)
}
test();

async和await 的错误的处理方法
我们可以通过给包裹await的async函数添加then/catch方法来解决

let promiseDemo = new Promise((resolve,reject)=>{
  setTimeout(()=>{
    let random = Math.random();
    if(random >= 0.5 ){
      resolve('sucess')
    } else {
      reject('failed')
    }
  }, 1000)  
})
async function test (){
  let result = await promiseDemo;
  return reslut
}
test().then(response => {
  console.log(response)
}).catch(error => {
  console.log(error)
})


相关文章

网友评论

      本文标题:ES7 中 async await

      本文链接:https://www.haomeiwen.com/subject/bwoixftx.html