节点:等待异步加载多个图像完成

时间:2019-03-01 19:20:28

标签: 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 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);
  });
}

有人可以分享一下这个信息吗!

非常感谢

2 个答案:

答案 0 :(得分:1)

地图正在返回一个承诺数组,以等待所有承诺解决后使用Promise.all()MDN reference link

(async () => {
   const urls = <array of urls>
   const promises = await urls.map(url => {
       const filename = path.basename(url);
       const localPath = imagesPath + '/' + filename;
       return loadImageToPath(url, localPath);
   });
   const responses = await Promise.all(promises)  // this line waits all promises to resolve
   console.log('done');
 })();

答案 1 :(得分:0)

我对代码进行了一些更改,现在可以正常工作了。我以为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();
        });
  });
}