浅谈ES6中的Async函数

转载地址:https://www.cnblogs.com/sghy/p/7987640.html

定义:Async函数是一个异步操作函数,本质上,Async函数是Generator函数的语法糖。async函数就是将 Generator 函数的星号(*)替换成async,将yield替换成await,仅此而已。

定义方式及调用方式

async function test(){
  const a = await fn1();
  const b = await fn2(a);
}
test()

由上可以看出:async函数不需要像 Generator 函数,需要调用next方法才能执行,其调用方式与普通函数调用方式一致

说明:a)async表示函数里有异步操作,await表示紧跟在后面的表达式需要等待结果

          b)async函数的返回值是 Promise

返回promise对象

async function test(a,b){
  const x = add(a,b);
  const y = add(1,x);
  return y;
}

function add(x,y){
  return x+y;
}

console.log(test(1,2))  //返回的是promise对象
test(1,2).then(value=>{
  console.log(value) //4 promise对象可以使用then()方法取得结果
})

Promise对象状态的变化:内部所有await命令后面的 Promise 对象执行完,才会发生状态改变,除非遇到return语句或者抛出错误。

  • return:状态改变为pending,调用then函数改变为resolve
async function f() {
  return 'hello world';
}

f().then(v => console.log(v))
// "hello world"
  • 抛出错误:状态直接改变为reject
复制代码
async f(){
  await add(1,2);
  throw new Error('出错了');
}

function add(x,y){(resolve,reject)=>{
  resolve(x+y)
}}
f()
.then(v=>console.log(v))
.catch(e=>console.log(e))  //出错了    reject状态会被catch方法捕捉到
复制代码

await命令:正常情况下,await命令后面是一个 Promise 对象。如果不是,会被转成一个立即resolve的 Promise 对象

async function f() {
  return await 123;
}

f().then(v => console.log(v))
// 123

错误处理:如果await后面的异步操作出错,那么等同于async函数返回的 Promise 对象被reject。防止出错的方法,就是将其放在try...catch代码块之中。

复制代码
async function main() {
  try {
    const val1 = await firstStep();
    const val2 = await secondStep(val1);
    const val3 = await thirdStep(val1, val2);

    console.log('Final: ', val3);
  }
  catch (err) {
    console.error(err);
  }
}
复制代码

使用注意点

  • 最好把await命令放在try...catch代码块中
  • 多个await命令后面的异步操作,如果不存在继发关系,最好让它们同时触发。
复制代码
// 写法一
let [foo, bar] = await Promise.all([getFoo(), getBar()]);

// 写法二
let fooPromise = getFoo();
let barPromise = getBar();
let foo = await fooPromise;
let bar = await barPromise;
复制代码
  • await命令只能用在async函数之中,如果用在普通函数,就会报错。

猜你喜欢

转载自www.cnblogs.com/520BigBear/p/12719968.html