Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript restler how to block/wait on a request

https://github.com/danwrong/restler http://nodejs.org/

in order to download a file, I am using restler from nodejs in a server-side script (not from a client web browser).

I could use the async way to fire an event when the download is completed, as follows:

rest = require('./restler');
rest.get('http://google.com').on('complete', function(result) {
  if (result instanceof Error) {
    sys.puts('Error: ' + result.message);
    this.retry(5000); // try again after 5 sec
  } else {
    sys.puts(result);
  }
});

but I prefer to use a sync way this time.

how can I call this and block/wait until I get the response?

and how to get the data or error afterwards

var req = rest.get('http://twaud.io/api/v1/users/danwrong.json');
// how to block/wait here until file is downloaded
if (req.response instanceof Error) {  // this does not worn neither
  ...
} else {
  ...
}
like image 949
David Portabella Avatar asked Jul 09 '13 00:07

David Portabella


1 Answers

I think you're looking for a library like Step, which will make restler appear synchronous.

You provide it a series of functions, so that you can write your code in a more linear fashion.

var rest = require('restler');
var Step = require('step');
var sys = require('sys');

function retry(millis) {
    console.log('Queing another try');
    setTimeout(download, millis);
}

function download() {
    Step(function() {
            // 1
            console.log('Starting download');
            rest.get('http://google.com').on('complete', this);
        },
        function(result) {
            // 2
            console.log('Download complete');
            if (result instanceof Error) {
                sys.puts('Error: ' + result.message);
                retry(5000); // try again after 5 sec
            } else {
                sys.puts(result);
            }
            return result;
        },
        function(result) {
            // 3
            console.log("This won't run until after Download is complete");
        });
}
download();
like image 105
Ozten Avatar answered Nov 19 '22 20:11

Ozten