3

I wrote JavaScript like this:

var keys=null;
var promise=Promise.promisify(alchemyapi.keywords("url",myUrl,{},function(response) {
    var keywords = { url:myUrl, response:JSON.stringify(response,null,4), results:response['keywords'] };
                return keywords;
            }));
promise.then(
                (result)=>{
                    var keys=result;
                    console.log(keys);
                },
                (error)=>console.log(error)
            );

I'm using AlchemyAPI and trying to store data I got into my database How should I do?

necroface
  • 3,365
  • 10
  • 46
  • 70
  • 2
    Unless you're using a Promise library, like Bluebird, there is no `Promise.promisify` ? – adeneo Feb 27 '16 at 19:25
  • Are you using Bluebird? And `Promise.promisify` does take a function as its argument and returns another function. You shouldn't pass it the result of a call, especially if it returns nothing. – Bergi Feb 28 '16 at 13:59

2 Answers2

4

You should be able to use Promise to return expected results by removing .promisify which is not a built-in Promise method ; substituting passing keywords to resolve within Promise constructor for return

var keys = null
, promise = new Promise(function(resolve) {
    alchemyapi.keywords("url", myUrl, {}, function(response) {
      var keywords = {url: myUrl
                      , response: JSON.stringify(response,null,4)
                      , results:response['keywords'] 
                     };
      resolve(keywords);
      // error handling ?
    })
  }).then(function(result) {
      keys = result;
      console.log(keys)
  }, function(err) {
      console.log(err)
  })
guest271314
  • 1
  • 15
  • 104
  • 177
4

For a more general Promise.promisify function without Bluebird, I ended up writing this:

function promisify(func) {
    return function promiseFunc(options) {
        return new Promise(function executor(resolve, reject) {
            func(options, function cb(err, val) {
                if (err) {
                    return reject(err);
                } else {
                    return resolve(val);
                }
            });
        });
    }
}

Hopefully someone else finds this helpful, but in most cases it's probably worth importing Bluebird.

Nick Benes
  • 1,334
  • 15
  • 14
  • nobody has ever explained to me why Bluebird exists or is needed now that Promises are native - I mean, why wouldn't native promises just do the same things? – Michael Oct 23 '18 at 03:24
  • 3
    @Michael, here's a quick take on that: https://medium.com/@housecor/5-reasons-to-keep-using-bluebird-for-promises-a4f59c8a5d69 – Nick Benes Nov 20 '18 at 03:31