等待不暂停执行

时间:2019-11-21 19:30:09

标签: node.js async-await fastify

我不知道执行为什么会继续,并且直到被调用的函数返回之前,wait不会暂停执行。

在node.js应用程序中

Contacts.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返回?

1 个答案:

答案 0 :(得分:3)

await的整个重点在于,您不必使用回调。相反,它只会将数据返回给您或在拒绝时引发错误。您需要选择一个,仅使用回调或仅使用异步/等待。

话虽这么说,异步/等待仅适用于诺言。但是mysql库不使用promise。因此,如果您使用的是mysql而不是mysql2,则无论如何在这种情况下都无法使用async / await。

此外,回调不会返回任何内容。 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');