gpt4 book ai didi

javascript - Node.Js API 等待 dynamodb 调用完成以发送到浏览器

转载 作者:太空宇宙 更新时间:2023-11-04 03:16:52 25 4
gpt4 key购买 nike

我有大量复杂的代码用于 dynamodb 调用数据库。基本上,我有几个数据库调用相互链接,然后最重要的是我需要循环访问多个项目。然后最后我需要能够向前端发送一个新的 JSON 对象以正确显示。问题是映射在数据库调用完成之前完成,因此“newItems”变量未定义。基本上,我需要 map 等待数据库完成,然后再进行下一次迭代。

代码片段不是完整的调用,但它是相关区域。这也全部包含在 app.get() 中。

        const newItems = items.map(function(item, i) {
dynamoDb.scan({
TableName: GIVEAWAY_ENTRIES_TABLE,
FilterExpression: "giveawayId = :giveawayId",
ExpressionAttributeValues: {
":giveawayId": item.id
}
}, (error, ge_result) => {
dynamoDb.scan({
TableName: USERS_TABLE,
FilterExpression: "sessionId = :sii",
ExpressionAttributeValues: {
":sii": sessionId
}
}, (error, result) => {
dynamoDb.scan({
TableName: GIVEAWAY_ENTRIES_TABLE,
FilterExpression: "giveawayId = :giveawayId and userId = :userId",
ExpressionAttributeValues: {
":giveawayId": item.id,
":userId": result.Items[0].id
}
}, (error, gemc_result) => {

console.log("RESPONSEEEEEEE");
return {
id: item.id,
title: item.title,
thumbnail: item.thumbnail,
photo: item.photo,
description: item.description,
myCount: gemc_result.Count,
totalCount: ge_result.Count
}
});
});
})

console.log("END OF MAPPPPP");

});

console.log("#######", newItems);
res.json({'success': true, data: newItems});

最佳答案

我推荐你的第一件事是使用原生函数promisify使AWS sdk函数返回一个promise。它更具可读性!然后你可以利用node.js的promise来处理异步代码,你可以这样使用它:

const util = require('util');
const safePromisify = function (fun, methodsArray) {
const suffix = 'Async';
methodsArray.forEach(method => {
fun[method + suffix] = util.promisify(fun[method]);
});
}
safePromisify(dynamoDb, ['scan']);

const newItems = items.map(function async(item, i) {
// ^^^^^ this is required to use await

// Note the async and await keywords
let ge_result = await dynamoDb.scanAsync({
TableName: GIVEAWAY_ENTRIES_TABLE,
FilterExpression: "giveawayId = :giveawayId",
ExpressionAttributeValues: {
":giveawayId": item.id
}
});

let result = await dynamoDb.scanAsync({
TableName: USERS_TABLE,
FilterExpression: "sessionId = :sii",
ExpressionAttributeValues: {
":sii": sessionId
}
});

let gemc_result = await dynamoDb.scanAsync({
TableName: GIVEAWAY_ENTRIES_TABLE,
FilterExpression: "giveawayId = :giveawayId and userId = :userId",
ExpressionAttributeValues: {
":giveawayId": item.id,
":userId": result.Items[0].id
}
});

return {
id: item.id,
title: item.title,
thumbnail: item.thumbnail,
photo: item.photo,
description: item.description,
myCount: gemc_result.Count,
totalCount: ge_result.Count
}
});

Note: You have to append the word Async on the function call

关于javascript - Node.Js API 等待 dynamodb 调用完成以发送到浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55248762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com