繁体   English   中英

javascript async await 我不明白它是如何工作的

[英]javascript async await I don't understand how it works

嗨,我正在更深入地研究 Javascript async/await,但我有一些我不明白的代码。

在这段代码中,我首先将数组 [1,2,3,4] 发送给名为 timeCall 的函数,然后再次将其发送给 [5,6,7,8]。 所以,我希望代码工作的方式是

1 2 3 4
h e l l o
5 6 7 8
h e l l o

你好,为什么

1 5
h e l l o
2 6
h e l l o 

我不确定这是否是这样处理的。 如果我用map代替for of语句,1到8完成后,hello反复出现。 我现在想,当我遇到 await 时,我会继续执行微任务并发送下面的 5 6 7 8。 我认为没有什么问题

1 2 3 4 你好 5 6 7 8 ....

如何修改代码以输出这样的数据?

 const timeArrs = [ 'h', 'e', 'l', 'l', 'o' ] function time(arr) { return new Promise((res, rej) => { setTimeout(() => { res(console.log(arr)); }, 3000); }) } function timeArrProcessing(arr) { return new Promise((res, rej) => { setTimeout(() => { res(console.log(arr)); }, 2000); }) } function hi() { return Promise.all(timeArrs.map(async(arr) => { await timeArrProcessing(arr); })); } async function timeCall(arrs) { for(const arr of arrs) { await time(arr); await hi(); } console.log('End'); } timeCall([1, 2, 3, 4]); timeCall([5, 6, 7, 8]);

正如评论中提到的,你的代码有几个问题......首先,调用一个异步函数会立即启动它在“后台”运行,它不会阻止其他代码,所以这些行只是踢关闭将同时运行的两个 timeCall 实例

timeCall([1, 2, 3, 4]);
timeCall([5, 6, 7, 8]);

如果您希望第一个在运行第二个之前完成,则需要等待它。 但是由于 await 仅适用于异步函数,您可能需要一个异步 iife来运行它们

(async()=>{
  await timeCall([1, 2, 3, 4]);
  await timeCall([5, 6, 7, 8]);
})()

您还在每个元素完成后添加了 hi 函数,而不是在它们全部完成后,因此您可能希望将 timeCall 更改为:

async function timeCall(arr) {
  for(const elem of arr) {
    await time(elem);
  }
  await hi();
}

另外 - 看起来您可能希望 hi 在 'hello' 中的字母之间暂停? 如果是这样,你将需要这样的东西:

async function hi() {
  for(const elem of timeArrs) {
    await timeArrProcessing(elem);
  }
}

因此,将所有这些放在一起,请尝试以下操作,看看它是否适合您:

 const timeArrs = [ 'h', 'e', 'l', 'l', 'o' ]; (async()=>{ await timeCall([1, 2, 3, 4]); await timeCall([5, 6, 7, 8]); console.log('End'); })() async function timeCall(arr) { for(const elem of arr) { await time(elem); } await hi(); } function time(elem) { return new Promise((res, rej) => { setTimeout(() => { res(console.log(elem)); }, 3000); }) } function timeArrProcessing(arr) { return new Promise((res, rej) => { setTimeout(() => { res(console.log(arr)); }, 2000); }) } async function hi() { for(const elem of timeArrs) { await timeArrProcessing(elem); } }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM