【问题标题】:JavaScript - run function in for loop but wait for function completed [closed]JavaScript - 在for循环中运行函数但等待函数完成[关闭]
【发布时间】:2022-11-04 21:48:15
【问题描述】:

我需要编写一个 javascript for 循环,其中将执行相同的函数,但 i++ 只能在循环中的函数结束时发生

例子 :

function test($parameter) {};

for (let index = 0; index < array.length; index++) {
test(array[index]; // but need to wait to function ended
                
            }

请问有可能吗?

多谢

【问题讨论】:

  • 除非test 是异步的。

标签: javascript


【解决方案1】:

为此,您需要使 test 函数异步。

例如:

async function test($parameter) {
    // Some code that takes time
};

for (let index = 0; index < array.length; index++) {
    test(array[index]);      
}

【讨论】:

  • 嗨,谢谢,但我收到一个错误:Uncaught SyntaxError: await is only valid in async functions, async generators and modules
  • 为什么要异步?如果test 已经是同步的,那么将async 添加到添加await 是没有意义的。如果test具有异步行为,然后添加 async 不能保证使函数“等待”。取决于内部完成了什么异步任务。可能需要进一步的转变。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-15
  • 2017-05-10
  • 1970-01-01
  • 2021-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多