【问题标题】:Dojo xhr chainingDojo xhr 链接
【发布时间】:2013-07-07 03:32:34
【问题描述】:

我有以下延迟对象:

var base = xhr.get({
    url: config.baseUrl + base_query,
    handleAs: "json",
    load: function(result) {
        widget.set('value', result);
    },
    error: function(result) {
    }
});

当这个 GET 请求完成后,我需要使用第一个 base 的结果的 URL 执行第二个请求:

var d1 = base.then(
    function(result) {
        xhr.get({
            url: config.baseUrl + result.id,
            handleAs: "json",
            load: function(result) {
                widget.set('visibility', result);
            },
            error: function(result) {
            }
        })
   },
   function(result) {
   }
);

它工作正常。但是我如何根据base 结果提出不是一个而是两个或多个请求(如d1)?是否可以将任何d1d2、...、dn 组合到一个延迟对象中,并使用then 将其连接到base 对象?

【问题讨论】:

    标签: javascript dojo promise deferred


    【解决方案1】:

    是的,没错。你可以无限次拨打thenbase

    var d1 = base.then(fn1),
        d2 = base.then(fn2),
        …
    

    请注意,虽然它目前可以正常工作,但您的 d1 并不代表任何结果 - 链已断开,因为您没有从回调中返回任何内容。您实际上应该返回第二个请求的承诺:

    var base = xhr.get({
        url: config.baseUrl + base_query,
        handleAs: "json"
    });
    base.then(widget.set.bind(widget, 'value'));
    // or:    dojo.hitch(widget, widget.set, 'value') if you like that better
    
    var d1 = base.then(function(result) {
        return xhr.get({
    //  ^^^^^^
                url: config.baseUrl + result.id,
                handleAs: "json"
        });
    });
    d1.then(widget.set.bind(widget, 'visibility'));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-11
      • 2015-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多