[英]Javascript async functions in loop
I have following code with async function download_file(), its working correctly only where runs as single, but in loop, it's not waiting end of iteration.我有以下带有异步 function download_file() 的代码,它仅在单个运行时才能正常工作,但在循环中,它不会等待迭代结束。 https://pastebin.com/PRgJRn9i
https://pastebin.com/PRgJRn9i
(async () => {
for (let year of years) {
for (let month of months) {
for (let r of day_rng) {
await download_file(year, month, r);
}
}
}
})();
i am assuming you want each iteration to wait for the download_file
function to end, if so then your download_file
function should return a Promise
that resolved whenever you are done downloading and done writing the contents as per your code, currently its not returning anything so the await
before it won't do anything.我假设您希望每次迭代都等待
download_file
function 结束,如果是这样,那么您的download_file
function 应该返回一个Promise
,只要您按照代码解决任何问题,当前都不会返回任何内容,因此它的内容下载完成了在它不会做任何事情之前await
。
Simply add await
to make nodejs wait for the result.只需添加
await
即可让 nodejs 等待结果。
await (async () => {
for (let year of years) {
for (let month of months) {
for (let r of day_rng) {
await download_file(year, month, r);
}
}
}
})();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.