我遇到了node.js的问题,并使用AWS api获取有关RDS实例的信息。大多数信息在页面呈现时返回,但在API调用数据库之前"标记"完成后,数据库将返回到页面。
var dbInstances = [];
var rds = new AWS.RDS();
rds.describeDBInstances({}, function(err, data) {
if (err) console.log(err);
//loop through all databases that were returned and pull out the info we need.
data.DBInstances.forEach(function(dbInstance) {
dbInstance.Name = dbInstance.DBInstanceIdentifier;
dbInstance.Status = dbInstance.DBInstanceStatus;
//we need to look up the tags for the current db instance.
rds.listTagsForResource({ResourceName: dbInstance.DBInstanceArn},
function(tagerr, tagdata) {
//loop through all the tags of the specified db instance.
if (tagerr) console.log(tagerr);
if (tagdata !== null) {
var tags = tagdata.TagList || [];
tags.forEach(function(tag) {
//Look to see if the database has the "Group" tag
if (tag.Key === "Group") {
dbInstance.Group = tag.Value;
}
});
}
});
//put it in our databases array.
dbInstances.push(dbInstance);
});
//prepare view model
var viewObj2 = {
"region": regionObj.Name,
"dbInstances": dbInstances
};
//render view model.
res.render('instances', viewObj2);
});
});
呈现页面时,我有以下信息:
NAME GROUP STATUS
Db1 running
Db2 stopped
Db3 running
....
正如您所看到的,我的' Group'信息全部丢失,因为node方法在" rds.listTagsForResource"之前返回数据库数组。通话完成。我已经能够在我的代码中弄清楚其他异步性相关的错误,并使用回调来解决它们。但是无论我如何在这个特定的代码块中设置回调,我都没有得到我需要的数据。
我该如何使这项工作?
是的,我通过记录它确认了dbInstance标记。 :)
答案 0 :(得分:1)
查看promise variants in the SDK例如rds.listTagsForResource(res).promise()
然后使用标准Promise.all()等待承诺得以实现。