首页 > 解决方案 > 如何在 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发布请求不起作用

函数被调用并打印“函数被调用”但它不打印“历史已被删除”

标签: javascriptnode.jspost

解决方案


因为您正在调用函数,然后在函数执行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) 
    }
  });

}

推荐阅读