回调函数中nodeJS中变量的范围
问题描述:
这是来自我的应用程序的一个nodeJS代码块,用于在AWS Lambda中发布。该callProcess功能基本上返回关于我路过这个城市的一些处理的信息 - 即callProcess已经工作 -回调函数中nodeJS中变量的范围
function speech2(intent, session, callback) {
let country;
const repromptText = null;
const sessionAttributes = {};
let shouldEndSession = false;
let speechOutput = 'old text';
callProcess('New York', function (error, data) {
if (!error) {
speechOutput = data;
console.log(speechOutput);
}
else {
console.log(error.message);
}
});
// Setting repromptText to null signifies that we do not want to reprompt the user.
// If the user does not respond or says something that is not understood, the session
// will end.
callback(sessionAttributes,
buildSpeechletResponse(intent.name, speechOutput, repromptText,
shouldEndSession));
}
的执行console.log(speechOutput)正确显示有关城市所处理的信息在这里硬编码为“纽约” 。然而,在这个函数结尾有语音输出的回调仍然指的是'旧文本',即我无法使用位于函数内的处理过的信息来覆盖变量?我如何在回调中做到这一点?
这里的任何帮助,非常感谢。提前致谢。
答
您的callProcess函数是一个可以正确显示speechOutput数据的异步函数。您所调用的回调函数在执行callProcess之前调用的callProcess函数之外。 您可以通过调用callProcess函数内的回调来获得speechOutput的正确值。 这样-`
callProcess('New York', function (error, data) {
if (!error) {
speechOutput = data;
console.log(speechOutput);
callback(sessionAttributes,
buildSpeechletResponse(intent.name, speechOutput, repromptText,
shouldEndSession));
}
else {
console.log(error.message);
}
});
进一步信息异步方法的行为来看看这个async and sync functions
'callProcess()'是异步的(我认为),那么你的回调直到你在最后调用'callback()'后,才会触发'callProcess'。您需要在callProcess()回调中调用'callback()'来捕获该值。 –