1

I have this code:

createOrUpdate({
    test: 'test'
}).then((response) => {
    console.log(response);
});

which will expect a createOrUpdate to return a promise. Here is the createOrUpdate function:

function createOrUpdate(requestParams) {

    var options = {};

    return getService('global', function(error, serviceResult) {
        if (error) {
            log.error(error);
            return callback(error, null);
        }

        //...

        return requestPromise(options);
    });

}

I have this getService method that takes some paramaters and a call back. I need to get that return requestPromise(options) to return when createOrUpdate is called, but currently it is not working. I get an error saying I cannot call then on what createOrUpdate returns.

Ideas?

Soatl
  • 10,224
  • 28
  • 95
  • 153
  • Shouldn't you assign getService() to a variable, say: `var func = getService(...)` and then have: `return func()`? – Jakub Jankowski Sep 14 '16 at 14:02
  • `getService()` doesn't return a promise so when you do `return getService()` you don't get a promise that you can use. You probably want to promisify `getService()`. – jfriend00 Sep 14 '16 at 14:06
  • Sadly it was marked as duplicate while I was typing.. So I can't add it as an answer. https://gist.github.com/WORMSS/a6bbfa94ad9a3aa99b03c0d9f461ff3b – WORMSS Sep 14 '16 at 14:18

1 Answers1

0

Simple, you need to make getService into a promise returning API.

Otherwise, node-callback taking functions don't return anything and ignore their own return values.

function createOrUpdate(requestParams) {

    var options = {};

    return fromCallback(getService)('global').then(options => 
        requestPromise(options);
    );

}
Community
  • 1
  • 1
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • What if I cannot make getService a promise returning API? – Soatl Sep 14 '16 at 14:28
  • @PepperedLemons then you wrap it in one. – Benjamin Gruenbaum Sep 14 '16 at 14:29
  • Yup. Looks like bluebird makes it easy! http://bluebirdjs.com/docs/api/promise.fromcallback.html – Soatl Sep 14 '16 at 14:44
  • @PepperedLemons look at `promisifyAll` it's even nicer. – Benjamin Gruenbaum Sep 14 '16 at 14:49
  • Where does `fromCallback()` come from? I know Bluebird has such a function, but it's `Promise.fromCallback()` and you don't make any mention of Bluebird in your answer. – jfriend00 Sep 14 '16 at 16:36
  • I didn't mention bluebird because it's not required - I referenced an answer that shows how to convert a callback API and then just used "fromCallback" here as a descriptive name to what that answer does (for the node callback example). OP _can_ use bluebird and its `fromCallback` or they can use the code or logic from the answer linked above. If you think I should clarify further please let me know. – Benjamin Gruenbaum Sep 14 '16 at 21:33