node.jssynchronous

Synchronous http request in node js?


I'm looking for a simple way to perform synchronous http-requests in node.js, but it's still getting async responses ...

I've realised that node.js is recommended to async jobs, but in my case, I need the synchronous response to call other functions that use this data, if it's null/undefined, I can't proceed with the flow... What's the better way to do that?

Here's my code:

function callCellId(data) {
  console.log("Data: " + data);
  var towers = [],
      rscp = [];
  var request = require('sync-request');
  for (var x = 0; x < data.length; x++) {
    console.log("Request data: \n");
    rscp[x] = data[x].rscp;
    var res = request('POST', 'http://opencellid.org/cell/get?key=xxxxx&mcc=' + data[x].mcc + '&mnc=' + data[x].mnc + '&lac=' + data[x].LAC + '&cellid=' + data[x].cellID + '&format=json');
    console.log("loop " + x);
    data = res.getBody().toString();
    console.log("rsp: " + data);
    towers[x] = {
      'latitude': data.lat,
      'longitude': data.lon,
      'rscp': rscp[x],
      'signal': data.averageSignalStrength
    };
  }
  console.log("Content for triangulation" + JSON.stringify(towers));
  return towers;
}

Solution

  • Using async in a loop cloud be tricky.

    I solved this without external libraries using generators:

     LoopOperation: function() {
    
            //define generator with the main loop
            var loopIterator = function*() {
                for (var index = 0; index < 10; index++) {
                  var result = yield asyncOperation( (res) => loopIterator.next(res)); //do something asyc and execute () => loopIterator.next() when done as callback
                  console.log(result);
                }
            }();
    
            loopIterator.next(); //start loop
        }