Promise.promisify is not a function

8.6k Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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)
  })
2
On

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.