Jim*_*ton 3 javascript node.js promise
我正在使用Node.js对noSQL DynamoDB进行异步调用.我首先查询该帐户所属的"好友列表".这可能会从零返回到'n'个新主键,其中包含每个好友列表的所有成员的列表.把它们想象成一个人所属的俱乐部......你可能没有或很多; 每个俱乐部都有几个成员甚至一个成员.
到目前为止(我在这里第一次使用Promise ...虽然我在之前的JA项目中使用了回调)但我对我的位置没问题,但我知道我正在组装承诺数组不正确.也就是说,我可以在控制台中看到.then函数在两个promises解析之前执行.为了记录,我确实希望...任何.then可能满足于单一的承诺解决似乎是合理的.
无论如何,有人可以提供一些关于如何构建的提示吗?我想最终得到伪:
getBuddyLists .then(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);
});
};
Run Code Online (Sandbox Code Playgroud)
编辑:添加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);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5862 次 |
| 最近记录: |