Node.js 节点:等待异步多个映像加载完成
我知道以前也有人问过类似的问题。我仍然不能解决我的问题。在执行另一部分代码之前,我需要加载一组图像Node.js 节点:等待异步多个映像加载完成,node.js,http,async-await,Node.js,Http,Async Await,我知道以前也有人问过类似的问题。我仍然不能解决我的问题。在执行另一部分代码之前,我需要加载一组图像 (async () => { const urls = <array of urls> await urls.map(url => { const filename = path.basename(url); const localPath = imagesPath + '/' + filename; return loadImageToPa
(async () => {
const urls = <array of urls>
await urls.map(url => {
const filename = path.basename(url);
const localPath = imagesPath + '/' + filename;
return loadImageToPath(url, localPath);
});
console.log('done');
})();
async function loadImageToPath(url, localPath) {
const file = fs.createWriteStream(localPath);
return await http.get(url, function (response) {
console.log('Image loaded: ' + localPath);
response.pipe(file);
});
}
(异步()=>{
常量URL=
等待url.map(url=>{
const filename=path.basename(url);
const localPath=imagesPath+'/'+文件名;
返回loadImageToPath(url,localPath);
});
console.log('done');
})();
异步函数loadImageToPath(url、localPath){
const file=fs.createWriteStream(localPath);
return wait http.get(url、函数(响应){
log('Image-loaded:'+localPath);
管道(文件);
});
}
有人能分享一些关于这个的信息吗
非常感谢Map正在返回一个承诺数组,要等待所有承诺解析,请使用
Promise.all()
(异步()=>{
常量URL=
const promises=等待url.map(url=>{
const filename=path.basename(url);
const localPath=imagesPath+'/'+文件名;
返回loadImageToPath(url,localPath);
});
const responses=await Promise.all(promises)//此行等待所有承诺解析
console.log('done');
})();
我对代码做了一些更改,现在可以使用了。我认为http本身正在返回一个承诺。使用一个返回承诺的包装器,它现在可以工作了
(async () => {
const urls = <array of urls>
await urls.map(url => {
const filename = path.basename(url);
const localPath = imagesPath + '/' + filename;
return loadImageToPath(url, localPath);
});
console.log('done');
})();
async function loadImageToPath(url, localPath) {
const file = fs.createWriteStream(localPath);
return new Promise((resolve, reject) => {
http.get(url, function (response) {
console.log('Image loaded: ' + localPath);
response.pipe(file);
resolve();
});
});
}
(异步()=>{
常量URL=
等待url.map(url=>{
const filename=path.basename(url);
const localPath=imagesPath+'/'+文件名;
返回loadImageToPath(url,localPath);
});
console.log('done');
})();
异步函数loadImageToPath(url、localPath){
const file=fs.createWriteStream(localPath);
返回新承诺((解决、拒绝)=>{
get(url,函数(响应){
log('Image-loaded:'+localPath);
管道(文件);
解决();
});
});
}
我尝试了这段代码,但仍然获得了“完成”输出,然后将图像加载并保存到本地路径的输出。它首先需要加载和存储所有图像。
(async () => {
const urls = <array of urls>
await urls.map(url => {
const filename = path.basename(url);
const localPath = imagesPath + '/' + filename;
return loadImageToPath(url, localPath);
});
console.log('done');
})();
async function loadImageToPath(url, localPath) {
const file = fs.createWriteStream(localPath);
return new Promise((resolve, reject) => {
http.get(url, function (response) {
console.log('Image loaded: ' + localPath);
response.pipe(file);
resolve();
});
});
}