2017-11-11 133 views
0

這是來自我的應用程序的一個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)正確顯示有關城市所處理的信息在這裏硬編碼爲「紐約」 。然而,在這個函數結尾有語音輸出的回調仍然指的是'舊文本',即我無法使用位於函數內的處理過的信息來覆蓋變量?我如何在回調中做到這一點?

這裏的任何幫助,非常感謝。提前致謝。

+0

'callProcess()'是異步的(我認爲),那麼你的回調直到你在最後調用'callback()'後,纔會觸發'callProcess'。您需要在callProcess()回調中調用'callback()'來捕獲該值。 –

回答

0

您的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