Function works, but not when util.promisify () is used?

I have code using node-bing-api . It works erroneously and works fine , but I would like to convert it to using Promises (and await ).

I am using node 8 and util.promisify . In the code below, Bing.web is regular err-first code, and searchBing is a promising version.

 var findParentDir = require('find-parent-dir'), configDir = findParentDir.sync(__dirname, 'config.js'), config = require(configDir+'config.js'), util = require('util'), log = console.log.bind(console), Bing = require('node-bing-api')({ accKey: config.cognitiveServices.bingSearch }), searchBing = util.promisify(Bing.web); var start = async function(){ // This fails // var searchResultsRaw = await searchBing('windows', {top: 5}) // log(searchResultsRaw) // This works Bing.web('windows', {top: 5}, function(err, searchResultsRaw){ log(searchResultsRaw) }) }; start(); 

The promised version is not fulfilled:

 (node:1752) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: this.searchVertical is not a function 

This is a bug inside node -bing-api. But shouldn't util.promisify easily pass parameters to the real Bing.web using the same arguments as the original function?

Why does this function not work if it was promised?

Note. I can create my own propositional version that works, but I do not want to create additional code:

 var searchBing = function(){ return new Promise(function(resolve, reject) { Bing.web('windows', {top: 5}, function(err, searchResults){ if ( err ) { reject(err) return } resolve(searchResults) }) }) } 
+5
source share
1 answer

There is probably no context: the Bing.web function uses this in its body, which is not bound to Bing when using util.promisify .

You need to explicitly bind it through:

 searchBing = util.promisify(Bing.web.bind(Bing)); 
+10
source

Source: https://habr.com/ru/post/1269763/


All Articles