我想让 httpntlm
模块返回一个 promise ,它是通过回调实现的。
这是一个带有回调的工作版本:
httpntlm.get({
url,
username: 'username',
password: 'banana'
},
function (err, resx){
if(err) console.log(err);
else {
console.log(resx.headers);
console.log(resx.body);
}
});
这是我试图让它返回 promise 的方法:
promisify(httpntlm.post(config, (error, response) => {
if (error) return errro
return response
}))
.then(res => console.log(res))
.catch(err => console.log(err))
但是 promisify 版本返回错误:
UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_ARG_TYPE]: The "original" argument must be of type Function. Received type undefined
我缺少什么?谢谢
最佳答案
这就是docs say to util.promisify
:
util.promisify(original)
- original
<Function>
- Returns:
<Function>
如错误消息所述
The "original" argument must be of type Function, Received type undefined
你做了什么:
promisify(httpntlm.post(config, (error, response) => {
if (error) return error
return response
}))
您已经调用了该函数。和httpntlm.post
作为一个异步函数,它不返回任何内容。
您应该传递该函数:
var httpntlmPostAsync = promisify(httpntlm.post);
// if `post` depends on `this`
var httpntlmPostAsync = promisify(httpntlm.post.bind(httpntlm));
仅此而已。
换句话说,promisify
不会为您调用函数,也不会对正在运行的函数调用应用任何魔法。它创建了一个行为不同的新函数。
httpntlmPostAsync({
url: 'url',
username: 'username',
password: 'banana'
})
.then(res => console.log(res))
.catch(err => console.log(err))
或者,如果您更喜欢这样:
async function foo() {
try {
var res = await httpntlmPostAsync({
url: 'url',
username: 'username',
password: 'banana'
});
console.log(res);
} catch (err) {
console.log(err);
}
}
<小时/>
要 promise 多个功能,您可以使用如下内容:
['get', 'post', 'etc'].forEach(method =>
httpntlm[method + 'Async'] = promisify(httpntlm[method].bind(httpntlm))
);
之后,httpntlm.getAsync
, httpntlm.postAsync
等可用。
关于node.js - es6-promise:httpntlm 模块中的 promisify,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51875712/