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.

4
  • Promises do not make asynchronous code synchronous ... your result is determined asynchronously, but you return result synchronousluy Commented Jan 8, 2017 at 7:57
  • You probably need to read and study this: 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. Commented Jan 8, 2017 at 8:00
  • @JaromandaX thank you, it is the problem I'm learning now Commented Jan 8, 2017 at 8:07
  • @jfriend00, exactly the answer im looking for, thanks. Commented Jan 8, 2017 at 8:08

1 Answer 1

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);
      }
    });
  });
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.