0

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.

XYZ_Allen
  • 253
  • 2
  • 3
  • 15
  • Promises do not make asynchronous code synchronous ... your result is determined asynchronously, but you return result synchronousluy – Jaromanda X Jan 08 '17 at 07:57
  • You probably need to read and study this: [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call). It contains both options for plain callbacks and the use of promises. The main feedback here is that you have to learn how to program async. Tools like promises make async programming easier, but they do not make async programming into synchronous programming. You simply cannot return a value synchronously when the value comes from an async function. NO tool can help you do that. – jfriend00 Jan 08 '17 at 08:00
  • @JaromandaX thank you, it is the problem I'm learning now – XYZ_Allen Jan 08 '17 at 08:07
  • @jfriend00, exactly the answer im looking for, thanks. – XYZ_Allen Jan 08 '17 at 08:08

1 Answers1

2

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);
      }
    });
  });
}
XYZ_Allen
  • 253
  • 2
  • 3
  • 15