0
我完全不熟悉AWS數據庫,Node.JS和Express。我需要對AWS dynamodb數據庫進行多個查詢(彙總所有device_id計數並循環遍歷所有的bin)。下面我有我的代碼。查詢參數邏輯不完整,但我甚至無法確定異步邏輯在何處開始編譯並返回查詢以在API中輸出。Javascript異步數據庫查詢
我試過嵌套循環,但很快就意識到邏輯錯了,因爲所有的數據庫調用都是異步的。我嘗試使用async.map(),但無法弄清楚如何完成它。我應該重複一遍我爲aster.map()做的deviceIds,但將其嵌套在bin中?那麼如何將內部的async.map()值返回到外部呢?還是有沒有更好的做法,我甚至沒有想過?
如果任何人有任何額外的資源和/或基本框架的描述,我真的很感激它。
謝謝!
var getCoffeeHistogram = function() {
var counts = [];
var bins = fillRange(16);
var deviceIDs = fillRange(18);
var i;
for (i = 0; i < 16; i++) {
async.map(
deviceIDs,
function(deviceID, callback) {
var param = {
TableName: "iot-coffeecounts",
ExpressionAttributeValues: {
':id': "" + deviceID,
':time': "1"
},
ExpressionAttributeNames: {
"#ts": "timestamp"
},
KeyConditionExpression: "device_id = :id and #ts > :time"
};
docClient.query(param, function(err, data) {
if (err) {
console.log("Unable to query. Error:", JSON.stringify(err, null, 2));
} else {
console.log("Querying Succeeded for device");
}
callback(null, data.Count);
});
},
function(err, coffeeCounts) {
console.log(function(coffeeCounts) {
var total = 0;
for (count in coffeeCounts) {
total = total + count;
}
return total;
});
}
);
}
};
承諾和ES6'await/async'是最近馴服異步代碼的最簡單方法。 – Barmar