方法在完成函数执行之前返回值

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; 

}

此代码在完成方法执行之前从函数返回值。 我试图使用setTimeout,但结果仍然是一样的。 如何重新编写我的方法,直到方法执行完成才返回值。 我也尝试写回电话,但无法得到所需的结果(可能是我正在执行callback以错误的方式)

  • Slack-App-Watson:Watson从之前收到的消息中泄露意图
  • IBM Watson对话 - 无法将node.js连接到watson对话
  • 为什么当我在节点js中创build一个post调用时,Watson-conversation对任何请求都返回相同的默认响应
  • 沃森的谈话总是从根开始
  • 你可以使用Promise.all ,并用一个自定义的代码来说:“只要这些函数完成了,那就这样做”。

    例如…

     var message = ""; promise1 = new Promise((resolve, reject) => { setTimeout(() => { message += "my"; resolve(message); }, 2000) }) promise2 = new Promise((resolve, reject) => { setTimeout(() => { message += " first"; resolve(message); }, 2000) }) promise3 = new Promise((resolve, reject) => { setTimeout(() => { message += " promise"; resolve(message); }, 2000) }) var printResult = (results) => {console.log("Results = ", results, "message = ", message)} function main() { // See the order of promises. Final result will be according to it Promise.all([promise1, promise2, promise3]).then(printResult); Promise.all([promise2, promise1, promise3]).then(printResult); Promise.all([promise3, promise2, promise1]).then(printResult); console.log("\"\"" + message); } main(); 

    请参阅关于Promise的官方文档 。

    请参阅本教程以了解有关承诺的示例。

    您可以使用简单的callback来避免这种asynchronous性质。

      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); } updateMessage(payload,data,function(resultData){ if(resultData){ return res.json(resultData); } }); }); }); function updateMessage(input, response,callback) { if (!response.output) { response.output = {}; } else { if (response.intents.length > 0 && (response.intents[0].intent === 'rnr')) { getCalculationResult(response,function(result){ response=result; if(callback){ callback(response); return response; } }); } } } function getCalculationResult(response,callback){ 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(callback){ response.output[0].text = response.output[0].text + result; callback(response); return response; } } }