使用for循环和pg-bluebird

时间:2015-11-03 03:12:26

标签: node.js bluebird pg

如何使用pg-bluebird(https://github.com/aphel-bilisim-hizmetleri/pg-bluebird)合并for循环?

我想首先获取每个位置的id,纬度和经度(来自位置表)。然后,对于每个位置,我需要做一个http请求(这是我想要for循环的地方)。然后在我完成请求后,收到的数据应该插入到Aeris表中。

我是node.js的新手,只是了解承诺。我是否按照预期使用pg-bluebird?

这是我到目前为止所拥有的:

var request = require("request");
var Pgb = require("pg-bluebird");

exports.retrieve = function(){

  var pgb = new Pgb();

  var cnn;

  pgb.connect(DB_URL)
  .then(function (connection) {

    cnn = connection;
    var queryString = 'SELECT id, latitude, longitude FROM locations';

    return cnn.client.query(queryString);
 })
 .then(function (result) {

    console.log(result.rows);

    //this needs to run for each location 
    //this needs to access result.rows[0].id then 
    //result.rows[1].id and so on
    location_id = result.rows.id; 

    lat = result.rows.latitude;
    lng = result.rows.longitude;
    console.log("Lat=" + lat + " Lng=" + lng);
    var aerisUrl = AERIS_URL+
        "?p="+lat+","+lng+
        "&radius=10miles"+
        "&client_id="+CLIENT_ID+
        "&client_secret="+CLIENT_SECRET;

    request.get(aerisUrl,function(err,response,body){

        //do something with request data
    });

    return cnn.client.query();

})
.then(function (result, aerisResults) {
        //insert data in aeris table
        return cnn.client.query(queryString);
})
.then(function (result){

    console.log(result.rows);

    cnn.done();
})
.catch(function (error) {

      console.log(error);
});

1 个答案:

答案 0 :(得分:0)

首先,使用pg-promise与数据库进行通信。其次,您需要将您的http请求逻辑分离为一个返回promise的函数,这样您就可以将所有这些请求堆叠到一个数组中,然后通过promise.all执行。所有这些都显示在下面的代码中。

var request = require("request");
var promise = require("bluebird");
var pgp = require("pg-promise")({promiseLib: promise});

var db = pgp(DB_URL);

function createRequest(r) {

    var aerisUrl = AERIS_URL +
        "?p=" + r.latitude + "," + r.longitude +
        "&radius=10miles" +
        "&client_id=" + CLIENT_ID +
        "&client_secret=" + CLIENT_SECRET;

    return new promise.Promise(function (resolve, reject) {
        request.get(aerisUrl, function (err, response, body) {
            // do something with the request data and
            // then call either resolve(), if successful,
            // or reject(), if failed;
        });
    });
}

db.query("SELECT id, latitude, longitude FROM locations")
    .then(function (rows) {
        var req = rows.map(function (r) {
            return createRequest(r);
        });
        return promise.all(req);
    })
    .then(function (data) {
        // all http requests resolved successfully,
        // time to insert the data into table Aeris:
        return db.query("insert into Aeris(fields) values($1, $2,...)", [/*values*/]);
    })
    .then(function () {
        // successfully inserted data into table Aeris;

        // all done!
    })
    .catch(function (error) {
        // Ops, something failed;
        console.log("ERROR:", error);
    });