最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - why is await not working even when used in async function - Stack Overflow

programmeradmin5浏览0评论

I made a function to search a user by email id. I'm calling that function in an async function using await and assigning the returned value to or constant/variable but getting undefined on printing the constant/variable

function search(email) {
    sql = `SELECT email FROM users WHERE email = '${email}'`;
    db.query(sql, (err, res) => {
        if (err) {
            console.log(err);
        }
        else {
            return res[0].email;
        }
    })
}

const auth = async (req, res, next) => {
    try {
        const token = req.header('Authorization').replace('Bearer', '');
        const decoded = jwt.verify(token, 'catisdoguniversaltruth');
        const user = await search(decoded._id);
        console.log(user);
        if (!user) {
            throw new Error();
        }
        next();
    }
    catch (e) {
        res.status(401).send("Not Authenticated, Please login");
    }
};

module.exports = auth;

I made a function to search a user by email id. I'm calling that function in an async function using await and assigning the returned value to or constant/variable but getting undefined on printing the constant/variable

function search(email) {
    sql = `SELECT email FROM users WHERE email = '${email}'`;
    db.query(sql, (err, res) => {
        if (err) {
            console.log(err);
        }
        else {
            return res[0].email;
        }
    })
}

const auth = async (req, res, next) => {
    try {
        const token = req.header('Authorization').replace('Bearer', '');
        const decoded = jwt.verify(token, 'catisdoguniversaltruth');
        const user = await search(decoded._id);
        console.log(user);
        if (!user) {
            throw new Error();
        }
        next();
    }
    catch (e) {
        res.status(401).send("Not Authenticated, Please login");
    }
};

module.exports = auth;
Share Improve this question edited Mar 18, 2019 at 11:51 planet_hunter 3,9861 gold badge29 silver badges42 bronze badges asked Mar 18, 2019 at 11:37 Kunal ShuklaKunal Shukla 811 gold badge2 silver badges7 bronze badges 2
  • See this answer – jro Commented Mar 18, 2019 at 11:40
  • 1 Possible duplicate of How do I return the response from an asynchronous call? – ponury-kostek Commented Mar 18, 2019 at 11:55
Add a ment  | 

1 Answer 1

Reset to default 6

You need search() to be a promise and not a function.

await waits for a promise to resolve.

Try this:

function search(email) {
  return new Promise((resolve, reject) => {
    sql = `SELECT email FROM users WHERE email = '${email}'`;
    db.query(sql, (err, res) => {
      if (err) {
        reject(err);
      }
      else {
        resolve(res[0].email);
      }
    })
  }) 
}

This will be resolved as promise and auth() will wait.

You could also build search() as async/await promise. Doesn't really matter as long as you return a promise resolve.

发布评论

评论列表(0)

  1. 暂无评论