Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/469.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用wait new Promise()时,for循环后的代码未执行_Javascript_For Loop_Async Await - Fatal编程技术网

Javascript 使用wait new Promise()时,for循环后的代码未执行

Javascript 使用wait new Promise()时,for循环后的代码未执行,javascript,for-loop,async-await,Javascript,For Loop,Async Await,我有一个异步函数,有一个循环: let z; let step = 100; for(z=0; z < (combinedData.length-1)/step; z += 1){ // FURTHER CODE } 除了没有显示“结束”,一切都是对的。 我检查过了,没有错误 //LONG CODE TO EXECUTE NOT PASTING BECAUSE IRRELEVANT 所以不用担心 我认为,这一错误就在于 if(!(i<a.length))return;

我有一个异步函数,有一个循环:

let z;
let step = 100;
for(z=0; z < (combinedData.length-1)/step; z += 1){
    // FURTHER CODE
}
除了没有显示“结束”,一切都是对的。 我检查过了,没有错误

//LONG CODE TO EXECUTE NOT PASTING BECAUSE IRRELEVANT
所以不用担心

我认为,这一错误就在于

if(!(i<a.length))return;

if(!(i这可以让您了解如何正确编码循环:

async function delayedFunc(i, index) {
  await new Promise(resolve => setTimeout(resolve, 100));
  console.log(i, index);
}

async function main(array) {
  for (const [index, item] of array.entries()) {
    await delayedFunc(item, index);
  }
  console.log('Done!');
}

main([1, 2, 3, 4, 5]);

循环后的代码不会执行,因为您不会解析或拒绝创建的
承诺


你说得对,这个
if(!(I)我如何在不使用
数组的情况下获取项的索引。indexOf(item)
?有没有办法?@SkillGG我更新代码以显示索引。你可以在其他类型的循环中对其进行编码。我只想展示如何使用async/await来实现你的目标。
if(!(i<a.length))return;
async function delayedFunc(i, index) {
  await new Promise(resolve => setTimeout(resolve, 100));
  console.log(i, index);
}

async function main(array) {
  for (const [index, item] of array.entries()) {
    await delayedFunc(item, index);
  }
  console.log('Done!');
}

main([1, 2, 3, 4, 5]);
if(!(i<a.length)){
    return rs(); // Returns and resolves your created promise
}