gpt4 book ai didi

javascript - Node.js 等待异步函数完成,然后继续执行其余代码

转载 作者:可可西里 更新时间:2023-11-01 09:34:57 27 4
gpt4 key购买 nike

在我的代码中,我有 2 个 for 循环执行一个异步函数(它在两个循环中是相同的函数),但是在这 2 个循环之后,代码必须等到它们执行,然后才能运行。这是我的代码:

for(var a = 0; a < videoIds.length; a++){
if(videoIds){
findVideo(videoIds[a], function(thumbnailPath, videoName){ // findVideo is the async function
// it returns 2 values, thumbnailPath and videoName
videoNames[a] = videoName; // and then these 2 values are written in the arrays
thumbnaildPaths[a] = thumbnailPath;
console.log('1');
});
}
}

// then the above code runs one more time but with different values, so I won't include it here (it's the same thing)
enter code here
console.log('3');
// the rest of the code
// writes the values from the loops to the database so I can't run it many times

如果我运行代码,我会在看到 1 之前看到 3(来自 console.log 函数)。但是正如我上面所说的,我必须等待循环结束才能继续。 findVideo() 函数只包含一个由 mongoose 提供的 Video.find({}) 方法,然后返回值 thumbnailPath 和 videoName。我需要做的是等待 2 个循环结束然后继续,但由于显而易见的原因,我不能将其余代码放在循环中!有没有什么办法解决这一问题?谢谢!

最佳答案

您可以使用回调,但我更喜欢 promises,因为它们很优雅。

利用 Promise.all() https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

function getVideo(id){
return new Promise(function(resolve, reject){
findVideo(id, function(thumbnailPath, videoName){
resolve({
name: videoName,
thumbnail: thumbnailPath
});
});
});
}

var promises = videoIds.map(function(videoId){
return getVideo(videoId);
});

//callback in then section will be executed will all promises will be resolved
//and data from all promises will be passed to then callback in form ao array.
Promise.all(promises).then(function(data){
console.log(data);
});

// Same for other list of tasks.

关于javascript - Node.js 等待异步函数完成,然后继续执行其余代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38058540/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com