繁体   English   中英

如何在Node.js中的异步/回调中编写此代码?

[英]How to write this code in async/callbacks in nodejs?

我正在尝试根据条件中的回调结果执行SQL查询,但是我无法编写代码。 那么有人可以提供一些信息如何使用异步/回调方法来做到这一点吗?

app.get('/resell-property', function(req, res) {
    var data = {}
    data.unit_price_id = 1;
    function callback(error, result) {
        if (result.count == 0) {
            return hp_property_sell_request.create(data)
        } else if (result.count > 0) {
            return hp_unit_price.findAll({
                where: {
                    unit_price_id: data.unit_price_id,
                    hp_property_id: data.property_id,
                    hp_unit_details_id: data.unit_details_id
                }
            })
        }
    }


    hp_property_sell_request.findAndCountAll({
        where: {
            unit_price_id: data.unit_price_id
        }
    }).then(function (result) {
        if (result) {
            callback(null, result);
        }
    });    
});

如何为此编写回调?

hp_property_sell_request.create(data) ,hp_unit_price.findAll({
    where: {
        unit_price_id: data.unit_price_id,
        hp_property_id: data.property_id,
        hp_unit_details_id: data.unit_details_id
    }
})

返回结果后,我要处理回调并执行以下查询:

if (result.request_id) {
    return hp_unit_price.findAll({
        where: {
            unit_price_id:result.unit_price_id,
            hp_property_id:result.property_id,
            hp_unit_details_id:result.unit_details_id
        }
    }).then(function(result) {
        if (result.is_resale_unit==0 && result.sold_out==0) {
            return Sequelize.query('UPDATE hp_unit_price SET resale_unit_status=1 WHERE hp_unit_details_id='+result.unit_details_id+' and  hp_property_id='+result.property_id)
        }
    })
}

您的问题太含糊,无法准确回答。 我假设您需要调用两个方法,第一个方法完成后应调用后者,并且您需要第二个方法中可用的第一个方法的结果。

现在,解决方案

请注意,回调和Promise是非常不同的方法。 只坚持一个而不混用回调和promise是非常明智的。 根据您的要求,我强烈建议您承诺避免回调地狱。

使用回调,解决方案看起来像

app.get('/resell-property', function(req, res) {
method1(req.body.id,function(err,result){
    return method2(result);
})
function method1(input1,callback(err,result)){
    try{
        var result=st.execute("query");
        return callback(null,result)
    }catch(error){
        return callback(error,null);
    }
}
function method2(input2){
    return input2;
}
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM