node.js - Node JS 嵌套函数被跳过

标签 node.js asynchronous amazon-dynamodb alexa

尝试从 Alexa Intent 读取 dynamoDB 表,当我执行以下代码块时 getItem() 方法被跳过

function alexaIntent(intent, session, callback) {
    var results = "";
    var params = {
        Key: {
            "name": {
                S: "aaa"
            }
        },
        TableName: "bbb"
    };
    console.log('1111111111111111111111111111111');

    /* Code from here till.....*/
    ddb.getItem(params, (err, data) => {
         console.log('inside');
        if (err) {
            console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
        } else {
            console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
       }
    });
    /* .....here is being skipped */

    console.log('2222222');

    callback(session.attributes,
        buildSpeechletResponseWithoutCard("I am the King!!", "", "true"));
}

我是异步编程新手,我是否缺少基本概念/理解?

我得到的输出是:

1111111111111111111111111111111
2222222

最佳答案

没有被跳过。它只是非阻塞。传递给 getItem 的第二个参数 ((err, data) => {...) 的全部目的是让您知道执行完成后。另外,您看不到 console.error("Unable to read item...console.log("GetItem success:"...) 的原因是因为您在等待 getItem 之前告诉 alexaIntent 已完成。

只需将最后一个回调调用移至提供给 getItem 的回调内部即可:

    ddb.getItem(params, (err, data) => {
             console.log('inside');
            if (err) {
                console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
                callback(session.attributes, buildSpeechletResponseWithoutCard("Error!!", "", "true"));
            } else {
                console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
                callback(session.attributes,
                   buildSpeechletResponseWithoutCard("I am the King!!", "", "true"));
           }
        });

关于node.js - Node JS 嵌套函数被跳过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48431829/

相关文章:

node.js - socket.io服务器可以与非socket.io客户端通信吗

javascript - 在 Node.js 中导入钩子(Hook)

node.js - H2O 可以与 node.js 一起使用吗(在 Electron 应用程序中独立/离线)

asynchronous - 我应该使用什么网络库来编写一个服务器来处理 300k 以上的客户端?

ios - Swift 4 中的 AWS DynamoDB updateItem 问题

amazon-web-services - AWS DynamoDB 如何计算 Query 的读取单元?

python-3.x - 使用 Dynamorm 在 Python 中构建 AWS SAM 嵌套应用程序

node.js - Sequelize连接和关系

c++ - 在命令循环旁边运行 boost::asio 异步服务器

c# - 如何在此上下文中使用 WebClient.DownloadDataAsync() 方法?