1

我无法弄清楚为什么继续执行,并且 await 不会暂停执行,直到被调用的函数返回。

在 node.js 应用程序中

联系人.js

async function routes (fastify, options) {
    fastify.get('/contact', async (req, reply) => {
        let lookup = require('../helpers/validate_school');
        let school_info = await lookup.validate(req.hostname.split('.')[0]);
        console.log('here: ', school_info);
        let school = school_info.school;
        ...
        reply.view('application/application.html', school);
    });
};

school.lookup.js

async function validate(hostname){
    const con = require('../../config/db').getDb();
    let ret = {};
    console.log('lets check for school info');
    await con.query('SELECT * FROM schools where identifier=? LIMIT ?', [hostname, 1], function(err, res, fields){
        if (err) throw err;
        if (res.length > 0){
            ret.school = JSON.stringify(res[0]);
            ...
            console.log('found: ', ret);
            return ret;
        } else {
            console.log('not found: ', ret);
            return ret;
        }
    });
};
module.exports = {validate: validate};

日志

lets check for school info
here:  undefined
found:  {
  school: '{"id":2,"name":"Second School","school_dbid":"2","primary_color":"purple","secondary_color":"lavender","tertiary_color":"green","quaternary_color":"blue","identifier":"school2","mascot_id":1,"created_at":"2019-11-20T05:22:16.864Z","updated_at":"2019-11-21T17:59:11.956Z"}',
  ...
}

在继续执行代码块之前,如何确保 lookup.validate 返回?

4

1 回答 1

3

整点await是让您不必使用回调。相反,它只会将数据返回给您或在拒绝时抛出错误。你需要选择一个,要么只使用回调,要么只使用 async/await。

话虽如此,async/await 仅适用于 Promise。但是该mysql库不使用承诺。因此,如果您正在使用mysql而不是mysql2.

另外,回调不会返回任何东西。Return 语句在异步方案中不起作用。

你有两个选择。处理回调的异步性,直接使用值:

con.query('SELECT * FROM schools where identifier=? LIMIT ?', [hostname, 1], function(err, res, fields){
    // The result cannot leave this callback.
    // Anything you need to do with the result must be done here.
});

或者,如果您正在使用mysql2,您可以使用这样的承诺:

const data = await con.promise().query('your query');
于 2019-11-21T19:44:41.417 回答