如何在Node JS中执行多个发布请求

时间:2018-08-03 07:37:42

标签: javascript node.js post

您好,我想根据某些条件进行多个发布请求。我正在尝试,但是我的代码无法正常工作。我有一个在线存储的数据库(Firebase)。我要做的是从在线获取数据并保存到localdb,然后删除在线数据。

这是我到目前为止所做的

request('http://my-url here', function (error, response, body) {
    console.log('error:', error);
    console.log('statusCode:', response && response.statusCode); Print the response status code if a response was received

    var data = [];
    var parse = JSON.parse(body);

    var ids =  Object.keys(parse);
     var i = 0;

   ids.forEach(function(id) {
   var unique_keys =  Object.keys(parse[id]);
        unique_keys.forEach(function(unique_key) {

            data[i] = [

                    parse[id][unique_key]["lat"],
                    parse[id][unique_key]["long"],



                ];
                i++;
   });

 });

    saveHistory(data, function (result) {

        console.log("successfully save into local db");
        removeDataFromOnlineDatabase
        process.exit();

    });





}); 

function removeHistoryFromOnlineDatabase(){

    var request = require("request");

   console.log("function get called");
    var options = { method: 'DELETE',
        url: 'url here',
        headers:
            { 'Postman-Token': '4a126ab8-9b3e-465d-b827-d4dd83923610',
                'Cache-Control': 'no-cache',
                'Content-Type': 'application/json' } };

    request(options, function (error, response, body) {
        if (error) throw new Error(error);

        console.log("history has been removed" + body);
    });

}

我已经尝试了以上代码,但是此功能removeHistoryFromOnlineDatabase的发布请求无效

该函数被调用并显示“函数被调用”,但不显示“历史记录已被删除”

2 个答案:

答案 0 :(得分:0)

因为您正在调用函数,然后在执行process.exit()之前,removeHistoryFromOnlineDatabase的立即行退出了进程。

请注意:-:我已删除了用于较小代码的选项JSON数据。


方法1:(使用Callback(仅回叫)

saveHistory(data, function (result) {

    console.log("successfully save into local db");
    removeDataFromOnlineDatabase(function(error, response){
       process.exit();
    })

});

function removeHistoryFromOnlineDatabase(callback){
  var request = require("request");
  console.log("function get called");
  var options = options;

  request(options, function (error, response, body) {
    if (error){
     callback(error, null); 
    } else {
     console.log("history has been removed" + body);
     callback(null, response) 
    }
  });
}

方法2:(使用Promise)(仅承诺)

var Q = require("q");

saveHistory(data, function (result) {
    console.log("successfully save into local db");
    removeDataFromOnlineDatabase()
    .then(function(){
      process.exit();
    }).catch(function(){
       console.log("ERROR IN REQUEST");
    });
});

function removeHistoryFromOnlineDatabase(){
  var request = require("request");
  console.log("function get called");
  var options = options;

  return Q.promise(function(resolve, reject){
    request(options, function (error, response, body) {
      if (error){
        reject(error);
      } else {
        console.log("history has been removed" + body);
        resolve(response) 
      }
    });
  });

}

方法3:(使用promise - Q.nfcall(回调+承诺)

var Q = require("q");

saveHistory(data, function (result) {
    console.log("successfully save into local db");
    Q.nfcall(removeDataFromOnlineDatabase)
    .then(function(){
      process.exit();
    }).catch(function(){
       console.log("ERROR IN REQUEST");
    });
});

function removeHistoryFromOnlineDatabase(callback){
  var request = require("request");
  console.log("function get called");
  var options = options;

  request(options, function (error, response, body) {
    if (error){
     callback(error, null); 
    } else {
     console.log("history has been removed" + body);
     callback(null, response) 
    }
  });

}

答案 1 :(得分:0)

process.exit();移到console.log("history has been removed" + body);下方