函数有效,但在使用util.promisify()时失败? [英] Function works, but fails when util.promisify() used?
问题描述
我有一些使用 node-bing-api 的代码. 这是错误优先,并且可以完美运行,但是我想将其转换为使用Promises(和await
).
I have some code using node-bing-api. It's err-first and works perfectly, but I'd like to convert it to using Promises (and await
).
我正在使用节点8和util.promisify
.在下面的代码中,Bing.web
是常规的err-first代码,而searchBing
是约定的版本.
I'm using node 8, and util.promisify
. In the code below, Bing.web
is the regular err-first code, and searchBing
is the promisified 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 promisified version fails with:
(node:1752) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: this.searchVertical is not a function
这是node-bing-api内部的错误.但是util.promisify
是否不应该使用与原始函数相同的参数将选项无缝地传递到真实的bing.web
上?
This is an error inside node-bing-api. But shouldn't util.promisify
be passing the options on to the real bing.web
seamlessly, using the same arguments as the original function?
为什么在启用时无法使用此功能?
请注意,我可以创建自己的承诺版本-可以运行-但我不想创建额外的代码:
Note I can make my own promisifed version - which works - but I'd rather not create extra 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)
})
})
}
推荐答案
它可能缺少上下文:函数Bing.web
在其主体中使用this
,当使用util.promisify
时该函数未绑定到Bing
.
It's probably missing context: the function Bing.web
is using this
in its body, which is not bound to Bing
when using util.promisify
.
您需要通过以下方式显式绑定它:
You need to explicitly bind it via:
searchBing = util.promisify(Bing.web.bind(Bing));
这篇关于函数有效,但在使用util.promisify()时失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!