简体   繁体   中英

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 :

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? Is it possible to combine any d1 , d2 , ..., dn in one deferred object and connect it using then to base object?

Yes, exactly. You can call then infinite times on 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. 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'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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