首页 > 解决方案 > 从数据库获取数据时 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

我知道我可能必须在函数中使用异步但是我真的很难让代码按顺序运行。如果有人能帮助我让代码按顺序运行,我将不胜感激。谢谢!

标签: javascriptnode.js

解决方案


您应该将这两个函数移动到一个单独的模块中(如果这还没有完成)并使它们像这样异步:

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);
        }
      });
  });
}


推荐阅读