Node js 承诺循环中的所有多个 api 调用

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

我是 Node js 新手。这里我在异步中调用多个 api 调用。但我想在所有通话完成后返回承诺。

function getChunkBatchDetailsResponse$(id,
  baseUri,
) {
  return new Promise((resolve) => {
   
    var options = {
      'method': 'POST',
      'url': `${configJSON.apigeeBaseUrl}/batch`,
      'headers': {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${userToken}`,
      },
      body:

    };
    request(options, function (error, response) {     
     
      if (response.body) {     

        for (let i = 0; i < totalNumberOfChunks; i++) {
        
          chunksArray.push(formData.buffer.subarray(chunkStart, chunkEnd));
          chunkStart = chunkEnd;
          chunkEnd = chunkStart + chunkSize;
          if (chunkEnd > totalFileSize) {
            chunkEnd = totalFileSize;
          }
        }
        let promiseAll = [];
        for (let i = 0; i < chunksArray.length; i++) {
          let chunkNumber = i + 1;

          //return new Promise((resolve) => {
          getChunkUploadResponse$(          ).then((response) => {
           
            logMessage(
              `Upload '${id}' took ${endUploadTime - startTime}ms to complete`,
            );

          });
          // resolve('chunk file uploaded');
          //});
        }
        // Promise.all(promiseAll);
      }

      resolve(batchMessage);
    });
  });

}


function getChunkUploadResponse$(
 
) {

  return new Promise((resolve) => {
   
    request.post(
      `${configJSON.apigeeBaseUrl}/UploadChunk`,
      {
        formData: {
          file: {
            value: buffer,
            options: {
              filename: directory.name + '.zip',
            },
          },
        },
        headers: {        
          Authorization: `Bearer ${userToken}`,
        },
      },
      (err, response) => {
        logMessage('err performing batch chunk upload.');
        logMessage(JSON.stringify(err));
        logMessage('response performing batch chunk upload');
        logMessage(JSON.stringify(response));

        if (err) {

          resolve({
            id,
            directory: directory.path,
            message: err,
            code: 500,
          });
        } else if (response) {
          const statusCode = response.statusCode;
          this.batchMessage = {
            id,
            directory: directory.path,
            message: response.statusMessage,
            code: statusCode,
          };
          if (statusCode === 201) {
            try {
              this.batchMessage.batch = JSON.parse(response.body);
              logMessage('Successfully performed a batch chunk upload');
              resolve(batchMessage);
            } catch { }
          } else if (statusCode === 413) {
            resolve({
              id,
              directory: directory.path,
              message: JSON.parse(response.body),
              code: 500,
            });

          }
          else {
            let message = '';
            try {
              message = JSON.parse(response.body);
            } catch {
              message = '';
            }
            batchMessage.message = message;
            logMessage('message performing batch chunk upload.');
            logMessage(message);
          }
          resolve(batchMessage);
        }
      },
    );
  });
}

如果所有调用都成功应该返回成功。如果一次调用也失败,应该返回错误。

node.js promise
1个回答
0
投票

您可以使用 Promise.all 等待所有 Promise 解决。

function getChunkBatchDetailsResponse$(id, baseUri) {
  return new Promise((resolve, reject) => {
    var options = {
      'method': 'POST',
      'url': `${configJSON.apigeeBaseUrl}/batch`,
      'headers': {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${userToken}`,
      },
      body: // Add your request body here
    };
    request(options, function (error, response) {     
      if (error) {
        reject(error); // Reject if there's an error
        return;
      }
      if (!response || !response.body) {
        reject(new Error('No response or empty body')); // Reject if no response or empty body
        return;
      }
      
      const chunksArray = [];
      const totalNumberOfChunks = /* calculate totalNumberOfChunks */;
      const chunkSize = /* calculate chunkSize */;
      let chunkStart = 0;
      let chunkEnd = chunkSize;
      const totalFileSize = /* calculate totalFileSize */;
      
  
      for (let i = 0; i < totalNumberOfChunks; i++) {
        chunksArray.push(formData.buffer.subarray(chunkStart, chunkEnd));
        chunkStart = chunkEnd;
        chunkEnd = chunkStart + chunkSize;
        if (chunkEnd > totalFileSize) {
          chunkEnd = totalFileSize;
        }
      }
      
      const promiseAll = chunksArray.map(chunk => {
        return getChunkUploadResponse$(chunk); // Call getChunkUploadResponse$ for each chunk
      });

      // Wait for all promises to resolve
      Promise.all(promiseAll)
        .then(() => {
          resolve(batchMessage); // Resolve with batchMessage once all uploads are successful
        })
        .catch(error => {
          reject(error); // Reject if any upload fails
        });
    });
  });
}

希望我正确理解了你的问题,这会有所帮助。祝你好运! :)

© www.soinside.com 2019 - 2024. All rights reserved.