javascript - 从数据库获取数据时 Javascript 代码未按顺序运行
问题描述
我有两个功能,如下所示。它本质上只是从数据库中获取数据。
function processRequest(query){
let dynamoData = getDynamoData(query);
console.log('abc')
}
function getDynamoData(key){
var params = {
TableName: 'test_table',
Key: {
'TWEET_KEY' : {S: String(key)}
}
};
// Call DynamoDB to read the item from the table
ddb.getItem(params, function(err, data) {
if (err) {
console.log("Error");
} else {
console.log("Successfully got data from table")
return data.Item;
}
});
}
目前,当我运行代码时,它会在控制台中打印以下内容:
abc
Successfully got data from table
但是,我需要它在打印Successfully got data from table
之前打印abc
。
我知道我可能必须在函数中使用异步但是我真的很难让代码按顺序运行。如果有人能帮助我让代码按顺序运行,我将不胜感激。谢谢!
解决方案
您应该将这两个函数移动到一个单独的模块中(如果这还没有完成)并使它们像这样异步:
async function processRequest(query){
let dynamoData = await getDynamoData(query);
console.log('abc')
}
async function getDynamoData(key){
var params = {
TableName: 'test_table',
Key: {
'TWEET_KEY' : {S: String(key)}
}
};
return new Promise((resolve, reject) => {
// Call DynamoDB to read the item from the table
ddb.getItem(params, function(err, data) {
if (err) {
console.log("Error");
reject(err);
} else {
console.log("Successfully got data from table")
resolve(data.Item);
}
});
});
}
推荐阅读
- events - Apache Flink 1.6.0 - StateTtlConfig 和 ListState
- javascript - 用于过滤表结果的搜索栏在 React 中超时
- json - TypeScript - 隔离模块和 JSON 导入
- hyperledger-composer - “无法添加具有 ID 的对象,因为对象已存在”但对象在游乐场测试环境中不可见
- javascript - 以编程方式生成/激活的文件输入并不总是触发 `input` 事件
- sql - MS Access SQL - 左加入只有唯一匹配的表
- html - 垃圾邮件程序和输入表单
- javascript - 找出一个元素是否定义了 CSS“悬停”伪类?
- python - 是否有一个参数可以在 start_http_server (prometheus_client) 而不是 / 中设置其他端点?
- c# - WPF 缩放或缩放精灵图像