javascript restler如何阻止/等待请求

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

为了下载文件,我在服务器端脚本中(而不是从客户端Web浏览器)使用nodejs中的restler。

下载完成后,我可以使用asynchronous方式来触发事件,如下所示:

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); } }); 

但是这次我更喜欢使用同步方式。

我怎么能打电话给这个阻止/等到我得到回应?

以及之后如何获取数据或错误

 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 { ... } 

我想你正在寻找像Step这样的库,这将使restler显示同步。

您提供了一系列函数,以便您可以更线性地编写代码。

 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();