This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
                                
                                    (6个答案)
                                
                        
                                2年前关闭。
            
                    
当我执行以下代码块时,尝试从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

最佳答案

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

只需将最后一个回调调用移至提供给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/

10-11 09:01