如何处理多个回调返回nodejs中的值?

时间:2016-10-19 07:53:22

标签: javascript node.js

我正在尝试基于回调结果执行sql查询,如果条件但我无法编写代码。所以请在代码中提供som信息

delayed(time)

在这个如何编写

的回调
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
                    }
                })

3 个答案:

答案 0 :(得分:2)

promise resolve函数只接受一个输入参数,因此如果你需要传入多个东西,你必须将它们包含在一个对象中。就像,如果你必须使用类似的东西:

'...Server='+serverName' ...'

如果所有的东西都不是承诺解决的结果,你就不能使用Promise all,你可能需要使用类似的东西。

免责声明:代码示例非常糟糕,但它解释了这个概念。

答案 1 :(得分:2)

我建议你学习Promises,尤其是Bluebird。 你可以宣传传统的回调方法。

我还会在不同的文件中创建模型级函数。这是一个例子。

<强> parent.js

const db = require("./connections/database");  // connection to database

const getChildForParent = function (parentId, childId, callback) {
    db.find({parent: parentId, child_id: childId}, "childrenTable", function(err, result) {
        if (err) {
            return callback(err);
        }
        return callback(null, result);
    });
};

<强> children.js

const db = require("./connections/database");  // connection to database

const getToysForChild = function (childId, callback) {
    db.find({toy_belongs_to: parentId}, "toysTable", function(err, result) {
        if (err) {
            return callback(err);
        }
        return callback(null, result);
    });
};

然后在控制器中你可以这样做:

const Bluebird = require("bluebird");
const Parent = require("./parent.js");
const Child = require("./child.js");

// Promisifying adds "Async" at the end of your methods' names (these are promisified)
Bluebird.promisifyAll(Parent); 
Bluebird.promisifyAll(Child);

// Just an example.
app.get("/parent/:parentId/children/:childId", function(req, res) {
    return Bluebird.try(function() {
         return User.getChildForParentAsync(req.params.parentId, req.params.childId);
    }).then(function(child) {
       return Child.getToysForChildAsync(child.child_id);
    }).then(function(toys) {
       // Do something with toys.
    });
});

当然,你可以做更多的事情,这不是唯一的方法。

您也可以使用Promise.all()。当您希望等待多个承诺完成时,此方法非常有用。

假设您有一个要获取的网址列表,并在获取所有数据后处理结果。

var urls = [url1, url2, url3, url4, url5 .......... ];
var Bluebird = require("bluebird");
var request = require("request"); // callback version library

Bluebird.promisifyAll(request);

// create a list which will keep all the promises
var promises = [];

urls.forEach(function(url) {
    promises.push(request.getAsync(url1));
});

// promises array has all the promises
// Then define what you want to do on completion.

Bluebird.all(promises).then(function(results) {
    // results is an array with result a url in an index

    // process results.
});

答案 2 :(得分:1)

我建议使用Promises来解决这个问题。如果您需要所有请求的所有结果,则完成所有请求后Promise.all()将为您执行此操作。你的基本看起来像那样:

var req1 = new Promise(function(res, rej){
    var req = new XMLHttpRequest()
    …
    req.addEventListener('load', function (e) {
        res(e);
    })

var req2 = //similar to the above

Promise.all([req1, req2, …]).then(function(values){
  //all requests are done here and you can do your stuff
});

你也可以使用新的fetch api,它会像这样创建Promise:

var req1 = fetch(…);
var req2 = fetch(…);
Promise.all([req1, re2, …]).then(…);