ES7 中 async await

2018-02-28  本文已影响0人  Wang_Yong

处理多个之间相互依赖的请求,使用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)
})


上一篇 下一篇

猜你喜欢

热点阅读