正在跳过Node JS嵌套函数

时间:2018-01-24 21:24:05

标签: 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

1 个答案:

答案 0 :(得分:3)

不被跳过。它只是non blocking。传递给(err, data) => {...的第二个参数(getItem)的重点是让您知道一旦执行完毕。此外,您无法看到console.error("Unable to read item...console.log("GetItem succeeded:" ...的原因是因为您在等待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"));
           }
        });
相关问题