0

我有以下延迟对象:

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

当这个 GET 请求完成时,我需要使用第一个结果的 URL 执行第二个请求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) {
   }
);

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

4

1 回答 1

3

对,就是这样。您可以then无限次调用base

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'));
于 2013-07-06T19:32:34.983 回答