async / await 和 Promise 的关系

背景:

1.异步回调地狱 callback hell;

2.Promise 是基于 then catch 的链式调用,但也是基于回调函数;

3. async / await 是同步语法去编写异步代码,彻底消灭回调函数,但它也只是一个语法糖,从语法层面去解决 回调地狱;

关系:

async / await 和 Promise 并不互斥,二者相辅相成。

async / await 并不能改变异步的本质( js是单线程的,异步需要回调,都是要基于 event loop 来实现)。

await 后面的代码,都可以看做是异步回调 callback 里的内容,都是异步的。

1.执行 async 函数,返回的是 Promise 对象;

2. await 相当于 Promise 的 then;

3.用 try...catch 捕获异常,代替了 Promise 的 catch;

async function fn() {
  return 100;
}
(async function () {
  const a = fn(); // Promise 对象
  const b = await fn(); // 100
})()
!(async function () {
  const p1 = Promise.resolve(200);
  const data = await p1; // await 相当于 Promise then
  console.log('data', data); // 200
})();

!(async function () {
  const data = await 300; // await 相当于 Promise.resolve(300)
  console.log('data', data); // 300 
})();

// try...catch 相当于 Promise catch
!(async function () {
  const p2 = Promise.reject('error');
  try {
    const data = await p2;
    console.log('data2', data);
  } catch (err) {
    console.log('err', err); // error
  }
})();

使用场景:

// 打印顺序
async function async1() {
  console.log('async1 start'); // 2
  await async2();
  // await 后面都可看作是 callback 里的内容,同步代码执行完毕 再执行异步内容
  console.log('async1 end'); // 5
};
async function async2() {
  console.log('async2'); // 3
}

console.log('script start'); // 1
async1();
console.log('script end'); // 4



// 打印顺序--进阶
async function async1() {
  console.log('async1 start'); // 2
  await async2();
  // await 后面都可看作是 callback 里的内容,同步代码执行完毕 再执行异步内容
  console.log('async1 end'); // 5
  await async3();
  // 下面是回调的内容
  console.log('async1 end end'); // 7
};
async function async2() {
  console.log('async2'); // 3
}

async function async3() {
  console.log('async3'); // 6
}

console.log('script start'); // 1
async1();
console.log('script end'); // 4

你可能感兴趣的:(JS,异步,javascript,前端,vue.js)