Search code examples
javascriptnode.jsasynchronouspromisebluebird

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. 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. So I try to mimic the way by doingconversation.message(...).then(function(response){result = response.output.text}), but it says conversation.message(...).then() is not defined.


Solution

  • Thanks to jfriend00's link, I fixed my logic and used the correct way to handle this async call.

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