javascript reSTLer 如何阻止/等待请求

标签 javascript node.js

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

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

我可以使用异步方式在下载完成时触发一个事件,如下所示:

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

关于javascript reSTLer 如何阻止/等待请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17538104/

相关文章:

javascript - 更改 map 中的标记

javascript - Amped Studio 2 - 声音引擎

javascript - 如何获取 google webmasters api (Node.js) 的访问 token

javascript - 使用 JavaScript 从 html 复选框接收信息

node.js - Node.js 中间歇性连接的文件上传

javascript - 将 vtype 添加到网格 EXT-JS 中的列

javascript - 无法使用 Javascript 变量

javascript - 我应该学习 ASP.NET AJAX、jQuery 还是两者都学?

node.js - 无法在 OS X 中通过终端安装 tsc

javascript - 我如何在 Node 上使用 Konva JS 将补间渲染到一系列 png 文件?