[英]Adding bluebird promise to NodeJS module, then function is not defined
I'm new to promise and bluebird, in my current project, I have to deal with a lot async API calls, therefore I want to use JS promise as my main tool. 我是promise和bluebird的新手,在我当前的项目中,我必须处理很多异步API调用,因此我想使用JS promise作为主要工具。 One of my imported module looks like this: 我导入的模块之一如下所示:
var Promise = require("bluebird");
var watson = Promise.promisifyAll(require('watson-developer-cloud'));
var conversation = watson.init();
exports.enterMessage = function (inputText) {
var result; //want to return
conversation.message({
input: {
"text": inputText
}
}, function(err, response) {
if (err) {
console.log('error:', err);
result = err;
}
else {
result = response.output.text;
}
});
console.log(result); //sync call, result === undefined
return result;
}
My question is how should I approach this question? 我的问题是我应该如何处理这个问题? I understand the example about using promise with IO such like fs. 我了解有关将fs等IO用于诺言的示例。 So I try to mimic the way by doing conversation.message(...).then(function(response){result = response.output.text})
, but it says conversation.message(...).then() is not defined. 因此,我尝试通过进行conversation.message(...).then(function(response){result = response.output.text})
来模仿这种方式。没有定义。
Thanks to jfriend00 's link, I fixed my logic and used the correct way to handle this async call. 感谢jfriend00的链接,我修复了我的逻辑,并使用了正确的方式来处理此异步调用。
Here is the fixed code: 这是固定代码:
//app.js
var Promise = require("bluebird");
var conversation = Promise.promisifyAll(require('./watson-conversation'));
conversation.enterMessage(currentInput).then(function(val){
res.send(val)}
).catch(function(err){
console.log(err)
});
});
//watson-conversation.js
var conversation = watson.init();
exports.enterMessage = function (inputText) {
return new Promise(function(resolve, reject){
conversation.message({
input: {
"text": inputText
}
}, function(err, response) {
if (err) {
console.log('error:', err);
reject(err);
}
else {
resolve(response.output.text);
}
});
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.