I'm trying to do async loop, where I do something and after it ends, I write to the console. It's look like that:
我在尝试异步循环,在那里我做一些事情,在它结束后,我写到控制台。这是这个样子:
const http = require('http');
async function load(link)
{
try{
http.get(link, response => console.log(`File: ${link}`));
}catch(e){
console.log('error');
}
}
async function loop(arrayOfLinks)
{
for(let link of arrayOfLinks)
load(link);
}
module.exports = (arrayOfLinks) => {
(async () => {
await loop(arrayOfLinks);
console.log('Files: '+arrayOfLinks.length);
})();
}
But, what I have:
但是,我有什么:
Files: 3
File: http://localhost:8000/1.jpg
File: http://localhost:8000/2.jpg
File: http://localhost:8000/3.jpg文件:3文件:http://localhost:8000/1.jpg文件:http://localhost:8000/2.jpg文件:http://localhost:8000/3.jpg
And what I want:
和我想要的:
File: http://localhost:8000/1.jpg
File: http://localhost:8000/2.jpg
File: http://localhost:8000/3.jpg
Files: 3文件:http://localhost:8000/1.jpg文件:http://localhost:8000/2.jpg文件:http://localhost:8000/3.jpg文件:3
Questions:
问题:
- Why
await
operator doesn't block the next step? - 为什么等待操作符不阻止下一步?
- How can I solve this?
- 我怎么解决这个问题?
Thanks
谢谢
1 个解决方案
#1
2
You need to make sure load
function returns Promise. http.get
by itself is not going to return it so you want to wrap it (or use promise based HTTP library, like fetch
, etc).
你需要确保load函数返回承诺。http。get本身不会返回它,所以您希望包装它(或者使用基于承诺的HTTP库,比如fetch等)。
Simple promise wrapper could look like this:
简单的承诺包装可以是这样的:
async function load(link) {
try {
return new Promise((resolve, reject) => {
http.get(link, resolve).on('error', reject)
})
.then(response => console.log(`File: ${link}`))
} catch (e) {
console.log('error', e.message);
}
}
async function loop(arrayOfLinks) {
for (let link of arrayOfLinks)
await load(link);
}
You also need to use await load(link)
in loop
.
您还需要在循环中使用wait load(link)。
#1
2
You need to make sure load
function returns Promise. http.get
by itself is not going to return it so you want to wrap it (or use promise based HTTP library, like fetch
, etc).
你需要确保load函数返回承诺。http。get本身不会返回它,所以您希望包装它(或者使用基于承诺的HTTP库,比如fetch等)。
Simple promise wrapper could look like this:
简单的承诺包装可以是这样的:
async function load(link) {
try {
return new Promise((resolve, reject) => {
http.get(link, resolve).on('error', reject)
})
.then(response => console.log(`File: ${link}`))
} catch (e) {
console.log('error', e.message);
}
}
async function loop(arrayOfLinks) {
for (let link of arrayOfLinks)
await load(link);
}
You also need to use await load(link)
in loop
.
您还需要在循环中使用wait load(link)。