node.js - promise 在使用列表时所有内容都不会按预期工作

标签 node.js

我希望回调在 Promise 全部完成时返回响应。我在 promise 一切之前得到了答复。 Batch List 响应为空,因为它是在 Promise all 之前返回的。

getByReferenceID(object, mode, limit, lastEvaluatedKey, callback){
        var results = {};
        var requestList = [];
        var batchList = [];
        var response = {};
       new Promise((resolve, reject) => {
            this.getRequestList(object, limit, lastEvaluatedKey,function (err, result) {
                console.log(result);
                results = result;
                if(err) {
                    reject();
                } else {
                    resolve();
                }
            });
        }).then(async () =>
        {
            requestList = requestList.concat(results.items);
            const runAsyncFunctions = async () => {
            var promises = [];
                requestList.map(async request => {
                    var promise = await this.getBatchList(request.requestID.S, mode, null, null, function(err, result) {
                        batchList = batchList.concat(result.items);
                    });
                    promises.concat(promise);
                });
               await Promise.all(
                    promises
                ).then(()=>{
                   response = {
                       "requests": requestList,
                       "batches": batchList,
                       "lastEvaluatedKey": results.LastEvaluatedKey
                   };
                   callback("", response);
               }).catch((error) => {
                console.log(error);
                });
            };
            await runAsyncFunctions();

        }).catch((error) => {
            callback(error, response);
        });
    }

最佳答案

promises 不是一系列的promise。

线路

var promise = await this.getBatchList(request.requestID.S, mode, null, null, function(err, result) {
    batchList = batchList.concat(result.items);
});

稍后执行

callback("", response)

我猜你想做这样的事情

var promises = [];

for (const request of requestList) {
  const promise = this.getBatchList(request.requestID.S, mode, null, null, function (err, result) {
    batchList = batchList.concat(result.items);
  });

  promises.push(promise);
}

await Promise.all(
...

关于node.js - promise 在使用列表时所有内容都不会按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58300573/

相关文章:

eclipse - 在 Eclipse 中使用 (*.p2f) 文件进行 NodeJS 配置

node.js - 在单元测试中模拟 es6 模块

mongodb - 如何在 Node.js 中使用 Mongoose 进行分页?

node.js - 在 Windows 7 中安装 Node.exe

node.js - 从 angular2 服务发送正文中的值

javascript - 将 MATLAB 连接到 Firebase 数据库

mysql - 如何在 sequelize 的同一查询中使用 AND 和 OR 运算符?

node.js - 如何使用 mongoose 聚合函数计算每个评分

node.js - Express js中的AWS s3文件上传: whats the difference between upload vs multipart upload

javascript - collection.find() 无法按预期工作 - Node.js 和 MongoDB