Dojo xhr chaining

Dojo xhr chaining

本文关键字:chaining xhr Dojo      更新时间:2023-09-26

我有以下延迟对象:

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对象?

没错。您可以在base:上无限次调用then

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