【发布时间】:2018-02-24 22:30:04
【问题描述】:
我在使用 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
....
如您所见,我的“组”信息全部丢失,因为节点方法在“rds.listTagsForResource”调用完成之前返回数据库数组。我已经能够在我的代码中找出其他与异步相关的错误,并主要使用回调来解决它们。然而,无论我如何在这段特定的代码中设置回调,我都没有得到我需要的数据。
我怎样才能做到这一点?
是的,我已经通过记录它们来确认存在 dbInstance 标签。 :)
【问题讨论】:
标签: node.js amazon-web-services asynchronous