从Promise返回值到Promise. all

Return value back from Promise to Promise.All

本文关键字:Promise all 返回值      更新时间:2023-09-26

我正在Node js Express中创建一个函数,该函数将由客户端调用以下载内容。

需要从不同的源下载内容,并且只有在所有下载完成后才需要发回响应(通过节点下载的内容被压缩并发回调用客户端)。因此,所有的下载函数都封装在Promise.all(download1(), download2(), download3())

中。其中一个下载函数不仅下载内容,而且还生成json并将其发送回main函数。main函数将其设置为响应头。

客户端调用的API函数如下所示

function downloadAll(request, response) {
    // Download content only after folders are created
    return createDirPromise.then(function (result) { 
       var statusJson = ... // somehow get the status json from download1() so that it can be send to the client 
       return Promise.all([download1(contentsJson), download2(contentsJson), download3(contentsJson)]);
    })
    .then(function (result) {
        return new Promise(function (resolve, reject) {             
        // Create zip. Here is the zip creation logic.  
        // Once zip is created, send it to client as a buffer
            zipdir(zipFolderPath, function (err, buffer) { 
            if (err) { 
               console.log('Error while zipping!!! '+JSON.stringify(err));
                    return reject({ data: null, resp_status_code: 500, resp_status_message: JSON.stringify(err)});
            }                        }
            console.log('Zipping successful');
            return resolve(
               { 
                 data: buffer, 
                 resp_status_code: 200, 
                 resp_status_message: "Zip succeeded", 
                 headers: statusJson
               });
        })
     })  
    .catch(function (error) { 
        return { 
            data: 'Error in any of above ' + error, 
            resp_status_code: 500, 
            resp_status_message: 'Error while zipping'
        }
}

这是download1函数的样子

function download1(contentsJson) {
    return new Promise(function(resolve, reject) {
            //set the status json here
            var statusJson = { "key1": "value1", "key2": "value2"};
            //do the download stuff here and return the statusJson
            console.log('Downloading complete, return the status so that it can be send to the client'); 
            resolve(statusJson);
       }

我知道如何将报头发送回客户端。我的挑战是如何在downloadAll函数中获得statusJson。download1函数从Promise.all()中调用。只要download1, download2和download3完成。然后执行'。我无法找到一种方法来获得数据(statusJson)由downloadAll内的download1返回。

我无法找到一种方法来获得数据(statusJson)由downloadAll内部的download1返回。

这是你在Promise.all()上的then回调中作为result接收的数组中的第一个条目:

function downloadAll(request, response) {
    return createDirPromise.then(function (result) { 
       return Promise.all([download1(contentsJson), download2(contentsJson), download3(contentsJson)]);
    })
    .then(function (result) 
        // **** Here, the result of download1 is result[0]
        var statusJson = result[0];

Promise.all收集承诺结果,并按照您给它的承诺顺序将它们返回到一个数组中。

(旁注:我想你在createDirPromise之后缺少了())

的例子:

// (Requires Promise support in your browser)
"use strict";
var createDirPromise = createPromiseFunction("createDirPromise");
var download1 = createPromiseFunction("download1");
var download2 = createPromiseFunction("download2");
var download3 = createPromiseFunction("download3");
function downloadAll(request, response) {
  return createDirPromise().then(function(result) {
      return Promise.all([download1(/*contentsJson*/), download2(/*contentsJson*/), download3(/*contentsJson*/)]);
    })
    .then(function(result) {
      // **** Here, the result of download1 is result[0]
      var statusJson = result[0];
      console.log("statusJson = '" + statusJson + "'");
    });
}
downloadAll();
function createPromiseFunction(name) {
  return function() {
    return new Promise(function(resolve) {
      setTimeout(function() {
        console.log("resolving " + name);
        resolve("result of " + name);
      }, Math.random() * 50);
    });
  };
}