JavaScript async

async 异常抛出捕获

async function 中 await 接受到的promise 如果返回的是reject() 如果这个async function中有多个await

那么返回reject的 await 将不会向下执行

如果需要想让他自动执行下去,那么必须捕获异常 

async function f(){
  await Promise.reject('错误')
  await Promise.resolve(console.log(1))
}
f()

catch 方法

async function demo(bool){
  return new Promise((resolve,reject)=>{
    try{
      if(bool) {
        return resolve(bool)
      }else{
        throw new Error(`promise err ${bool}`)
      }
    }
    catch(e){
      reject(e)
    }
  })
}

async function f(){
  await demo(true).then(resolve=>console.log(resolve))
  // await demo(false).catch(reject => console.log(reject)) 捕获异常,不会阻止 async 继续运行
  await demo(false).catch(reject => console.log(reject))
  await demo(true).then(resolve=>console.log(resolve))
}

f()

同步触发

// 同时触发
// 不存在继发
function fa(ms){
  setTimeout(()=>{
    console.log('fa')
  },ms)
}
function fb(ms){
  console.log(`${ms} fb`)
}

async function test (){
  let [a,b] = await Promise.all([fa(1000),fb(30000)])
}

test()

猜你喜欢

转载自my.oschina.net/u/3529405/blog/1814994