gpt4 book ai didi

node.js - 使用 node.js 'util' 进行 promisify 会返回错误

转载 作者:太空宇宙 更新时间:2023-11-03 22:57:53 24 4
gpt4 key购买 nike

我试图在一个文件中创建一个函数来返回一个 promise ,我将从另一个文件中调用它。我正在尝试使用“util.promisify”来包装该函数,但出现错误。这是代码和错误:

来 self 的“checkEmail.js”:

const Profile = require('../../models/profile');
const util = require('util');


var exports = module.exports = {};

exports.findEmail = util.promisify(checkEmail());


function checkEmail (email) {
Profile.findOne({ 'emails': { $elemMatch: { email_address: email } } }, (err, userEmail) => {
let conclusion = false;
if (err) {
console.log('Error in looking up an existing email');
} else {
if (userEmail) {
console.log('We found an existing owner for email: ' + email);
conclusion = true;
}
}
return conclusion;
})
}

在“profile.js”上调用它:

router.route('/addemail/:id')

// ADD EMAILS
.put(function (req, res) {


Profile.findOne({ 'owner_id': req.params.id }, function (err, profile) {
if (err)
res.send(err);

EmailCheck.findEmail(req.body.email_address).then((data)=>{
console.log('The answer is: ', data);
});

profile.emails.push({
email_type: req.body.email_type,
email_address: req.body.email_address
})
profile.save(function (err) {
if (err)
res.send(err);
res.json(profile);
});
});
});

我收到的错误是:

Config for: http://localhost:3000
internal/util.js:272
throw new ERR_INVALID_ARG_TYPE('original', 'Function', original);

如有任何帮助,我们将不胜感激。

最佳答案

为了 Promisify,您传递给 util.promisify 的函数必须:

Take a function following the common error-first callback style, i.e. taking a (err, value) => callback as the last argument, and returns a version that returns promise

因此,您可以 promisify Profile.findOne,或者将回调作为最后一个参数传递给 checkEmail

function checkEmail (email, callback) {
Profile.findOne({ 'emails': { $elemMatch: { email_address: email } } }, (err, userEmail) => {
let conclusion = false;
if (err)
return callback(new Error('Error in looking up an existing email'));

if (userEmail) {
console.log('We found an existing owner for email: ' + email);
conclusion = true;
}
return callback(null, conclusion);
})
}

然后你应该这样调用它:

exports.findEmail = util.promisify(checkEmail);

否则,您将把 checkEmail 的返回值传递给 .promisify,它不是遵循上面注释的样式的函数。

关于node.js - 使用 node.js 'util' 进行 promisify 会返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55209991/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com