Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
971 views
in Technique[技术] by (71.8m points)

async 函数里有多个 await 的执行顺序?

await 在得到结果前会阻塞后面的代码,我设想的是过 3 秒后打印 5,再过 3 秒打印 6,实际情况却是 3 秒后 5 和 6 一起打印,这是为什么呢?

const a = new Promise((res, rej) => {
  setTimeout(() => {
    res(5);
  }, 3000);
});
const b = new Promise((res, rej) => {
  setTimeout(() => {
    res(6);
  }, 3000);
});
async function func() {
  let num = await a;
  console.log(num);
  let num1 = await b;
  console.log(num1);
}
func();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
const a = new Promise((res, rej) => {
  setTimeout(() => {
    res(5);
  }, 3000);
});
const b = new Promise((res, rej) => {
  setTimeout(() => {
    res(6);
  }, 3000);
});
// 这里的时候,定时器已经触发。
async function func() {
  let num = await a;
  console.log(num);
  let num1 = await b;
  console.log(num1);
}
func();

因为你在最上面的时候两个setTimeout都触发了。

async function func() {
  let num = await new Promise((res, rej) => {
  setTimeout(() => {
    res(5);
  }, 3000);
});;
  console.log(num);
  let num1 = await new Promise((res, rej) => {
  setTimeout(() => {
    res(6);
  }, 3000);
});;
  console.log(num1);
}
func();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...