nodejs承诺在函数执行之前返回

问题描述 投票:0回答:1

我正在尝试调用 Promise.allSettled 中的 fetch 方法。但该方法返回的值为空。 fetch 需要时间,之前已返回响应。

期望的结果:我想要数组中的所有图像都是base64。但它返回为空。

有代码。

(async function getData() {
                    results = results.recordset;
                        let i = 0;
                        const result = await Promise.allSettled(results.map(async (record) => {
                            (async function getData() {
                                var file = record.Path.split('Images');
                                //file = file[1].replaceAll('\\','/');
                                var file_path = file[1].replaceAll('\\', '/') + "/" + record.FileName;
                                var img_url = "localhost"+file_path;
                                let file_data_response = await reportModel.fetchTiff(img_url);
                                let base64Image = Buffer.from(file_data_response, 'binary').toString('base64');
                                let imgSrc = "data:png;base64,"+base64Image;
                                //let imgSrc = '';
                                let imgImg = '<img src='+img_url+' alt="Remote Image" />';
                                console.log(imgImg);
                                response.img.push(imgImg);
                            })();
                        })).then((results) => {
                                                        
                        });
                    
                    return resolve(response);
                })();

exports.fetchTiff = function(image_url) {
    return new Promise((resolve, reject) => {
        var response = 0;
        (async function getData() {
            // let responsezz  = await axios.get(image_url, {responseType: 'arraybuffer'});//.then(res => {return resolve(res);})
            // response = await responsezz.data;
            let responsezz  = await fetch(image_url);
            response = await responsezz.blob();
            console.log(response);
            return resolve(response);
        })();
        
    });
}
node.js async-await promise fetch
1个回答
0
投票

主动重构你的代码,这样你就可以更好地了解如何处理这个问题:

// Main function to fetch and process image data
async function fetchAndProcessImages(results) {
  const response = { img: [] };
  results = results.recordset;

  // Using Promise.allSettled to handle each record asynchronously
  const fetchPromises = results.map(async (record) => {
    try {
      // Construct the image URL
      const imgUrl = constructImageUrl(record);

      // Fetch and convert the image to base64
      const base64Image = await fetchImageAsBase64(imgUrl);

      // Construct the image HTML and push it to the response
      const imgTag = createImageTag(base64Image);

      response.img.push(imgTag);

      return { status: "fulfilled", value: imgTag };
    } catch (error) {
      console.error(
        `Error processing image for record ${record.FileName}:`,
        error
      );
      return { status: "rejected", reason: error.message };
    }
  });

  await Promise.allSettled(fetchPromises);

  console.log("All images processed:", response.img);
  return response;
}

// Helper function to construct the image URL
function constructImageUrl(record) {
  const filePath = record.Path.split("Images")[1].replace(/\\/g, "/");
  return `http://localhost${filePath}/${record.FileName}`;
}

// Helper function to fetch the image and convert it to base64
async function fetchImageAsBase64(url) {
  const response = await fetchTiff(url);
  const arrayBuffer = await response.arrayBuffer();
  return Buffer.from(arrayBuffer).toString("base64");
}

// Helper function to create an image HTML tag from base64 data
function createImageTag(base64Image) {
  return `<img src="data:image/png;base64,${base64Image}" alt="Remote Image" />`;
}

// Fetch function to retrieve image data
async function fetchTiff(imageUrl) {
  try {
    const response = await fetch(imageUrl);
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response;
  } catch (error) {
    console.error(`Error fetching image from ${imageUrl}:`, error);
    throw error;
  }
}

module.exports = {
  fetchAndProcessImages,
  constructImageUrl,
  fetchImageAsBase64,
  createImageTag,
  fetchTiff,
};
© www.soinside.com 2019 - 2024. All rights reserved.