亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

沒有使用承諾下載圖像

沒有使用承諾下載圖像

回首憶惘然 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 關注
  • 114 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號