0

This is a nodeJS code nugget from my application, written for publishing in AWS Lambda. The callProcess function basically returns some processed information about the city I am passing - hard coded here for "New York"

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));
}

The console.log(speechOutput) correctly displays the processed information about the city - i.e. callProcess has worked. However the callback at the end of this function that has speechOutput is still referring to 'old text' i.e. I am unable to over-write the variable using the processed information that sits within the function? How do I do this within callbacks?

Any help here is greatly appreciated. Thanks in advance.

mkanywhere
  • 21
  • 1
  • 3
  • `callProcess()` is asynchronous (I assume), so your callback to `callProcess` isn't fired until after you call the `callback()` at the end. You will need to call `callback()` from within the `callProcess()` callback to capture that value. – Mark Nov 11 '17 at 18:46

1 Answers1

0

your callProcess function is an async function which correctly shows the speechOutput data. The callback you've wriiten is outside this callProcess function which is called before callProcess is executed. you can get the correct value of speechOutput by calling the callback inside your callProcess function. like this-`

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);
    }

});

for further info how async method behave have a look at this async and sync functions