jquery中的延迟链

时间:2016-11-03 13:44:13

标签: javascript jquery typescript jquery-deferred chaining

我需要在链中发出3个请求。因此,我使用jquery deffered。

Request 1 
-> on done if response contains expected result then Request 2 else return empty array/null
-> on done if response contains expected result then Request 3 else return empty array/null
private request1() {
    const vm = this;

    vm.isLoading(true);
    let deffer = system.defer(dfd => {dataService.getResponse1()
       .done((response) => {
              request2(response.collection))
              dfd.resolve();
       });

    return deffer.promise();
}

private request2(collection) {
     dataService.getResponse2(collection)
        .done((response) => request3(response.collection));
}

private request3(collection) {
     dataService.getResponse3(collection)
        .done((response) => saveResponse(response.collection));
}

private saveResponse(collection) {
    //do some stuff    
}

在构造函数中我将request1称为

vm.request1().done(() => {
      vm.isLoading(false);
});

问题是isLoading在调用false之前设置为saveResponse。在完成所有请求后,我应该如何正确地重构我的请求结构以更新isLoading

感谢。

2 个答案:

答案 0 :(得分:0)

尝试这种方式(请检查代码中的注释):

// Request 1 -> on done Request 2 -> on done -> Request 3

private request1() {
    const vm = this;

    vm.isLoading(true);
    let deffer = system.defer(dfd => {dataService.getResponse1()
       .done((response) => {
              // 1. Here you have to resolve the dfd promise after 
              // request2 promise is resolved. For this reason,
              // I added the call to "done()" method.
              request2(response.collection)).done((response2) => { dfd.resolve()});
       });

    return deffer.promise();
}

private request2(collection) {
     // 2. You need to return the promise returned by getResponse2
     return dataService.getResponse2(collection)
        .done((response) => request3(response.collection));
}

private request3(collection) {
     // 3. You need to return the promise returned by getResponse3
     return dataService.getResponse3(collection)
        .done((response) => saveResponse(response.collection));
}

private saveResponse(collection) {
    //do some stuff    
}

因此,在request3()中,您将返回getResponse3()返回的承诺,该承诺将返回saveResponse()方法中调用的done()返回的承诺。

request2()中,您返回getResponse()返回的承诺,而承诺将返回前一段中描述的request3()返回的承诺。

request1()中,在主done()回调中,您调用request2()并等待(使用done()),它会在解决主要承诺之前完成。

这样,vm.isLoading(false)request2完成后,应调用request3

答案 1 :(得分:0)

简短回答:在调用saveResponse后,将vm.isLoading(true);移到request3的主体内。