为了账号安全,请及时绑定邮箱和手机立即绑定

没有使用承诺下载图像

没有使用承诺下载图像

回首忆惘然 2022-10-27 15:08:02
我需要下载所有图像并用它们生成word文档。使用 nodeJS 和 MeteorWebApp.connectHandlers.use('/download', async function (req, res, next) {  // ...  const images = [];  await lines.forEach(async (line, k) => {    if (line.type && line.type === 'image') {      images.push({        id: line.id,        file: line.id + '.jpg',      });      download_image(line.imageUrl, line.id + '.jpg');    }  });  // ...  // Then I use images[] to insert them into a Word document.});const download_image = (url, image_path) =>  axios({    url,    responseType: 'stream',  }).then(    (response) =>      new Promise((resolve, reject) => {        response.data          .pipe(fs.createWriteStream(image_path))          .on('finish', () => resolve())          .on('error', (e) => reject(e));      })  );问题是在我将图像插入 Word 文档之前没有下载图像。如何在图像完成下载之前停止/等待?我不太擅长承诺。想念她什么?
查看完整描述

1 回答

?
元芳怎么了

TA贡献1798条经验 获得超7个赞

在其中使用函数.forEach(或类似的数组方法)是常见的错误。只是意味着它返回承诺和工作方式与async将承诺链接在一起的方式相同。因此,这条线只会创建并返回一堆 Promise,但它不会等待里面的所有 Promise 完成。async functionawaitthenwait lines.forEach(async (line, k) => {


WebApp.connectHandlers.use('/download', async function (req, res, next) {

  // ...


  const images = [];

  const promises = [];

  lines.forEach((line, k) => {

    if (line.type && line.type === 'image') {

      images.push({

        id: line.id,

        file: line.id + '.jpg',

      });


      promises.push(download_image(line.imageUrl, line.id + '.jpg'));

    }

  });

  // here you get array with all the images downloaded

  const downloadedImages = await Promise.all(promises);

  // this line will be executed after you download all images


  // ...

});


// This function would work same with or without the `async` keyword 

// (because async function return promise - you are returning the promise. 

// Async function allows to use await, but you are not using await in this function).

// However it is good practice to have all functions that returns promise 

// marked as `async` so you know that you receive promise from it.

const download_image = async (url, image_path) =>

  // Dont forget to return your promise otherwise you cannot await it

  return axios({

    url,

    responseType: 'stream',

  }).then(

    (response) =>

      new Promise((resolve, reject) => {

        response.data

          .pipe(fs.createWriteStream(image_path))

          .on('finish', () => resolve())

          .on('error', (e) => reject(e));

      })

  );


查看完整回答
反对 回复 2022-10-27
  • 1 回答
  • 0 关注
  • 75 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信