[英]Node: util.promisify() without callback as final parameter
I'm trying to use util.promisify()
to transform a function that uses a callback so I can call it with async/await: https://nodejs.org/dist/latest-v8.x/docs/api/util.html#util_util_promisify_original我正在尝试使用util.promisify()
来转换使用回调的 function 以便我可以使用 async/await 调用它: https://nodejs.org/dist/latest-v8.x/docs/api/util .html#util_util_promisify_original
So far I've been able to use it with functions that have the callback as the final parameter, as it expects.到目前为止,我已经能够将它与将回调作为最终参数的函数一起使用,正如它所期望的那样。 But I'm getting confused on how to use it when another item is the final parameter.但是当另一个项目是最终参数时,我对如何使用它感到困惑。
I have a function that structured like this:我有一个结构如下的 function:
myFunction = function(userID, company, callback, jwt) {
....
return callback(null, results)
}
Since the jwt
is the final parameter, how can I use promisify on this and still pass the jwt
?由于jwt
是最终参数,我如何在此使用 promisify 并仍然通过jwt
? I'd rather not change the structure of the original function because other places are calling it as-is我宁愿不更改原始 function 的结构,因为其他地方都按原样调用它
You can create a new function wrapper around your function that only accepts arguments in a different order in order to move the callback last:您可以在 function 周围创建一个新的 function 包装器,该包装器仅接受 arguments 以不同的顺序,以便最后移动回调:
const wrapper = (userID, company, jwt, callback) =>
myFunction(userID, company, callback, jwt);
const promisified = utils.promisify(wrapper);
For a more generic solution, you can use Lodash's rearg
that will change the order of arguments based on the array you give it:对于更通用的解决方案,您可以使用 Lodash 的rearg
,它将根据您给它的数组更改 arguments 的顺序:
const wrapper = _.rearg(myFunction, [0, 1, 3, 2]);
const promisified = utils.promisify(wrapper);
Working with the function:使用 function:
myFunction = function(userID, company, callback, jwt) {
/* ... */
return callback(null, results)
}
You have four options.你有四个选择。
util.promisify((userID, company, jwt, callback) => myFunction(userID, company, callback, jwt))
myFunction[util.promisify.custom] = function (userID, company, jwt) {
return new Promise((resolve, reject) => {
const callback = (err, result) => err ? reject(err) : resolve(result);
myFunction.call(this, userID, company, callback, jwt);
});
}
You can then use this with utils.promisify(myFunction)
and it will pull your custom implementation.然后,您可以将其与utils.promisify(myFunction)
一起使用,它将拉取您的自定义实现。
myFunction = function(userID, company, jwt, callback) {
/* ... */
return callback(null, results)
}
myFunction = function(userID, company, callbackOrJwt, jwtOrCallback) {
const [callback, jwt] = callbackOrJwt !== null && typeof callbackOrJwt === 'object'
? [jwtOrCallback, callbackOrJwt] // possibly called with jwt first
: [callbackOrJwt, jwtOrCallback]; // possibly called with callback first
/* ... */
return callback(null, results)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.