function rip(intent_update, output_rnr){
var headers_conv = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Basic YWFjZWU2M'
};
var dataString = '{ "output": { "text": { "values": [' + output_rnr + '] } } }';
var options_conv = {
url: 'https://watson-api-explorer.mybluemix.net/'+ intent_update + '?version=2017-05-26',
method: 'POST',
headers: headers_conv,
body: dataString
};
function callback_conv(error, response, body) {
if (!error && response.statusCode === 200) {
console.log(body);
}
}
request(options_conv, callback_conv);
}
app.post('/api/message', function(req, res) {
var workspace = process.env.WORKSPACE_ID || '<workspace-id>';
}
var payload = {
workspace_id: workspace,
context: req.body.context || {},
input: req.body.input || {}
};
// Send the input to the conversation service
conversation.message(payload, function(err, data) {
if (err) {
return res.status(err.code || 500).json(err);
}
return res.json(updateMessage(payload, data));
});
});
function updateMessage(input, response) {
if (!response.output) {
response.output = {};
} else {
if (response.intents.length > 0 && (response.intents[0].intent === 'rnr')) {
response = getCalculationResult(response);
}
}
return response;
}
function getCalculationResult(response){
var result = '';
if(response.intents[0].intent === 'rnr'){
var question = response.input.text;
var query = qs.stringify({q: question, ranker_id: ranker_id, fl: 'contentHtml'});
solrClient.get('fcselect', query, function(err, searchResponse) {
if(err) {
console.log('Error searching for documents: ' + err);
}
else {
result = JSON.stringify(searchResponse.response.docs[0].contentHtml, null, 1);
rip(response.intents[0].intent, result);
}
});
}
/*
* if(result === ''){
setTimeout(function(){
response.output.text[0] = result + response.input.text;
}, 15000);
}
else{
var output = result + response.input.text;
response.output.text[0] = output;
}
*/
response.output[0].text = response.output[0].text + result;
return response;
}
This code is returning values from functions before completing execution of method. I have tried to use setTimeout but still the result is same. How can re write my methods to wait until method execution is completed before a value is returned. I have also tried writing with call back but unable to get desired result(may be i am implementing call back in wrong way)
You can use
Promise.all
, and say with one custom code something like: "Just if these functions are completed, then, do this".For example...
See the Official documentation about Promises here.
See this tutorial to understand with examples about Promises.