如何在 if-condition 中处理异步调用

How to handle async call inside if-condition

如果 condition.not 将新名称存储在名称中并且 运行 回调优先

,则给定代码如何处理内部异步调用
var xyz = function (data, callback) {
    try{
        pool.query('select * from devices',[1],function(err,result){ 
            
            if(result.rows[0].name = 12){
                
                pool.query('select * from devices',[12],function(err,result){
                    result.rows[0].name = result.rows[0].newname;
                }
                
            }
            callback(result.rows[0].name);
        });
    }catch(err){
        callback(err);
    }
}

由于您标记了 async-await,您将需要使用 Promise

所以

像这样创建一个辅助函数

const promiseQuery = (pool, ...args) => new Promise((resolve, reject) => {
    pool.query(...args, (err, result) => {
        if (err) return reject(err);
        resolve(result);
    });
});

然后这样使用

var xyz = async function (data, callback) {
    try {
        const result = await promiseQuery(pool,'select * from devices', [1]);
        if (result.rows[0].name = 12) {
            const result = await promiseQuery(pool, 'select * from devices', [12]);
            result.rows[0].name = result.rows[0].newname;
            callback(result.rows[0].name);
        }
    } catch (err) {
        callback(err);
    }
}

当然,有些数据库已经有了他们功能的 promisified 版本

所以会像

var xyz = async function (data, callback) {
    try {
        const result = await pool.query('select * from devices', [1]);
        if (result.rows[0].name = 12) {
            const result = await pool.query('select * from devices', [12]);
            result.rows[0].name = result.rows[0].newname;
            callback(result.rows[0].name);
        }
    } catch (err) {
        callback(err);
    }
}