2017-09-15 68 views
0

我在使用node.js和使用AWS api獲取有關RDS實例的信息時遇到了問題。當頁面呈現時,大部分信息都會返回,但在數據庫「標記」的API調用完成之前,數據庫將返回到頁面。使用AWS api的節點JS異步調用

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標記通過登錄它們。 :)

回答