简体   繁体   English

Dojo XHR链

[英]Dojo xhr chaining

I have the following deferred object: 我有以下延迟对象:

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

When this GET request is completed I need perform the second request with URL which used result of the first base : 完成此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) {
   }
);

It works fine. 工作正常。 But how I can make not one but two or more request (like d1 ) based on base result? 但是,如何根据base结果而不是发出两个或多个请求(例如d1 )? Is it possible to combine any d1 , d2 , ..., dn in one deferred object and connect it using then to base object? 是否可以将任何d1d2 ,..., dn到一个延迟对象中, then使用then将其连接到base对象?

Yes, exactly. 对,就是这样。 You can call then infinite times on base : 您可以致电then在无限次base

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

Notice that while it currently may work fine, your d1 does not represent any result - the chain is broken as you're not returning anything from the callback. 请注意,尽管当前d1可能工作正常,但您的d1并不代表任何结果-链已断开,因为您没有从回调中返回任何内容。 You should return the promise for the second request actually: 您应该实际返回第二个请求的承诺:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM