JavaScript的承诺 – 创build一个承诺一起执行的数组

我正在使用Node.js对noSQL DynamoDB进行asynchronous调用。 我首先查询该帐户属于哪个“好友列表”。 这可能会从零返回到“n”个新的主键,其中将包含每个这些好友列表的所有成员的列表。 把他们想象成一个人所属的俱乐部……你可能没有或多less; 每个俱乐部有几个成员甚至一个。

到目前为止(我在这里第一次使用Promises …虽然我已经在之前的JA项目中使用了callback函数),但是我知道我在哪里,但是我知道我错误地组装了Promise数组。 也就是说,我可以在控制台中看到.then函数在两个promise均parsing之前执行。 为了logging,我确实期望……任何一个单独的承诺解决都可以得到满足似乎是合理的。

不pipe怎样,有人可以提供一些关于如何构build的提示? 我想结束伪:

getBuddyLists。然后(getAllTheBuddiesInTheLists).then(function(){// doSomething});

我的Node.js代码:

const AWS = require('aws-sdk'); const docClient = new AWS.DynamoDB.DocumentClient({region:'us-east-1'}); var buddyGroups = []; exports.handler = function(event, context, callback) { var params = { TableName: 'USER_INFORMATION', Key: { "DEVICE_ID": event.DEVICE_ID } }; var getBuddyList = new Promise(function(resolve, reject){ docClient.get(params, function(err, data){ if(err){ reject(err); } else{ var dataJSON = JSON.parse(JSON.stringify(data)); dataJSON.Item.my_buddies.values.forEach(function(value){ buddyGroups.push(value); }); console.log('Got buddy groups: ' + buddyGroups); resolve(buddyGroups); } }); }); getBuddyList.then(function(capturedData){ // capturedData => an array of primary keys in another noSQL document console.log('groups: ' + capturedData); var myPromises = []; capturedData.forEach(function(value){ var reqParams = { TableName: "buddy_list", Key: {"BUDDY_ID": value} }; myPromises.push(new Promise (function(resolve, reject){ docClient.get(reqParams, function(err, data){ if(err){ //console.log(err, data); reject(err); }else{ var returnedJSON = JSON.parse(JSON.stringify(data)); console.log(returnedJSON); resolve(returnedJSON); } }); })); }); // Promise.all(myPromises); // ADDED IN EDIT <<<<<<<<<<<<<<<<<<<<<< // how to make sure all of myPromises are resolved? // }).then(function(){ console.log("done"); }) .catch(function(err){ console.log("error message:" + error); }); }; 

编辑:添加Promise.all(myPromises)的位置;

只是为了澄清你将如何使用Promise.all ,即使你接受了答案,你编辑的问题,但仍然没有正确使用它

此外,讨论.map vs .forEach – 这就是你将如何使用.map

  getBuddyList.then(function(capturedData){ // capturedData => an array of primary keys in another noSQL document console.log('groups: ' + capturedData); // changes to use .map rather than .forEach // also, you need to RETURN a promise - your edited code did not return Promise.all(capturedData.map(function(value){ return new Promise (function(resolve, reject){ var reqParams = { TableName: "buddy_list", Key: {"BUDDY_ID": value} }; docClient.get(reqParams, function(err, data){ if(err){ //console.log(err, data); reject(err); }else{ var returnedJSON = JSON.parse(JSON.stringify(data)); console.log(returnedJSON); resolve(returnedJSON); } }); }); })); }).then(function(){ console.log("done"); }) .catch(function(err){ console.log("error message:" + error); }); 

你正在寻找Promise.all(myPromises) ,它返回一个承诺结果数组的单个承诺。