尝试从 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/