首页 文章

Node JS,NeDB - 如何使同步返回父模块

提问于
浏览
0

我有功能:

let isExistByEmail = (email) => {
    return new Promise(function (resolve) {
        db.count({email: email}, (err, n) => {
            resolve(n > 0);
        });
    }).then(result => {
        return result;
    });
};

如果我在其中制作console.log - >将是结果 . 但是,因为它的操作异步结果不会返回父模块 . 我需要验证,如果存在电子邮件返回错误,但我不能 . 我尝试make setTimeout并尝试使用async await,但没有结果 .

2 回答

  • 0

    我不确定你想要暗示什么 . 但据我所知,你不会得到结果 . isExistByEmail('email@email.com') 将返回Promise而不是您期望的布尔值 . then返回一个promise而不是obj / variable

  • 0

    我找到了下一个答案:使用async-await .

    async function isEmailExist(email) {
        let count = await new Promise((resolve, reject) => {
            db.count({email: email}, (err, count) => {
                if (err) reject(err);
                resolve(count);
            });
        });
        return count > 0;
    }
    

    并在通话中再次使用等待:

    async function isAccessData(req) {
        let errors = [];
    
        if (await users.isEmailExist(req.body.email) === true) {
        // doing
        }
     }
    

相关问题