异步函数


async

  • async 变体 (async(异步) 函数总是返回 Promises )
    // 异步函数声明
    async function foo() {}
    // 异步函数表达式
    const foo = async function () {};
    // 异步函数定义
    let obj = { async foo() {} }
    // 异步箭头函数 
    const foo = async () => {};
    
    // async(异步) 函数的 Promise 完成状态
    async function asyncFunc() {
      return 123;
    }
    asyncFunc()
    .then(x => console.log(x)); // 123
    
    // async(异步) 函数的 Promise 拒绝状态
    async function asyncFunc() {
      throw new Error('Problem!');
    }
    asyncFunc()
    .catch(err => console.log(err)); // Error: Problem!

async/await

function testAwait(){
  return new Promise((resolve) => {
    setTimeout(function(){
      console.log("testAwait");
      resolve();
    }, 1000);
  });
}
async function helloAsync(){
  await testAwait();
  console.log("helloAsync");
}

//await后面可以是Promise对象么 也可以是字符串,布尔值,数值以及普通函数
function testAwait(){
  setTimeout(function(){
    console.log("testAwait");
  }, 5000);
}
async function helloAsync(){
  await testAwait();
  console.log("helloAsync");
}

// await针对所跟的表达式不同,有两种处理方式:
// 1、对于Promise对象,await会阻塞主函数的执行,等待 Promise 对象 resolve,然后得到 resolve 的值,作为 await 表达式的运算结果,然后继续执行主函数接下来的代码。
// 2、对于非Promise对象,await等待函数或者直接量的返回,而不是等待其执行结果。

async/await并行/串行触发

function testAwait1(){
  return new Promise((resolve) => {
    setTimeout(function(){
      console.log("testAwait1");
      resolve();
    }, 1000);
  });
}
function testAwait2(){
  return new Promise((resolve) => {
    setTimeout(function(){
      console.log("testAwait2");
      resolve();
    }, 1000);
  });
}
async function test(){
  console.time("testTime")
  let pramiseFn1 = testAwait1();
  let pramiseFn2 = testAwait2();
  let res1 = await pramiseFn1;
  let res2 = await pramiseFn2;
  console.log("两个promise并行执行,done");
  console.timeEnd("testTime")
}
async function test1(){
  console.time("test1Time")
  let res1 = await testAwait1();
  let res2 = await testAwait2();
  console.log("两个promise串行执行,done");
  console.timeEnd("test1Time")
}

async/await在for循环中使用

function testAwait(id){
  return new Promise((resolve) => {
    setTimeout(function(){
      console.log("testAwait"+id);
      resolve(id);
    }, 1000);
  });
}

async function test(){
  console.time('start')
  let List = [1,2,3]
  let promises = List.map(id=>testAwait(id))
  for(let promise of promises) {
    let res = await promise
    console.log("promise结果:",res)
  }
  console.log("for循环promise,done")
  console.timeEnd('start')
}
test()

async/await捕获异常

function testPromise(){}
async testAsync() {
  try {
    await testPromise()
  } catch(err) {
    console.log(err)
  }
}

async/await与Generator

// Generator函数,可以多次返回
// yield暂停执行,next恢复执行
function* generatorFn() {
  yield '11111111';
  yield '22222222';
  return '33333333';
}
let test = generatorFn();
test.next(); // {value: '11111111', done: false}
test.next(); // {value: '22222222', done: false}
test.next(); // {value: '33333333', done: true}
test.next(); // {value: undefined, done: true}
// async是Generator函数的语法糖
// async函数就是将Generator函数的星号(*)替换成async,将yield替换成await
// async函数自带执行器,而Generator函数需要每次都调用next()来执行

Promise

var promise = new Promise(function (resolve, reject) {
    var a = 1
    if (a === 1) {
        resolve(a)
    } else {
        reject(error)
    }
})
promise.then(function (value) {
    console.log(value++)
    return value
}).catch(function (error) {
    console.log(error)
}).then(function (value) {
    console.log(value++)
})

文章作者: Damao
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Damao !
  目录