同步解决链式角度承诺

时间:2017-10-26 17:16:23

标签: javascript angularjs promise angular-promise

我有一个使用$ q服务的解析承诺函数,其中有一些通用代码可以根据特定条件解析/拒绝。我有一个场景,我必须在api1成功解决后才能执行api2。但这两个电话都是异步发生的。我已粘贴下面的伪代码。请帮忙。非常感谢。

var resolvePromise = function(promise)
{
    var defer = $q.defer();
    promise.then(function(response)
        if(certain conditions are true)
        {
             defer.reject(err)
        }
        defer.resolve();
    )
    .catch(function(errors){
        defer.reject(errors);
    })

   return defer.promise;
}

function synchronousCalls()
{
    var promise1 = service.getApi1();
    var promise2 = service.getApi2();

    return resolvePromise(promise1).then(function(){
          return resolvePromise(promise2);
    })
}

function getData()
{
    synchronousCalls().then(function(){
       console.log("synchronous run of apis ended");
    })
}

2 个答案:

答案 0 :(得分:2)

synchronousCalls更改为

function synchronousCalls()
{
    return service.getApi1().then(resolvePromise).then(service.getApi2).then(resolvePromise);
}

答案 1 :(得分:2)

您不需要resolvePromise功能。让getApi1getApi2直接返回Promise.then()。此外,调用返回Promise的函数不会停止执行上下文。您正在立即触发对两个API的调用,而不是等待第一个完成。您需要致电getApi1().then()应该从中返回Promise。请考虑以下代码:

// This says, fire them both immediately
var promise1 = service.getApi1();
var promise2 = service.getApi2();

// Your call should look something like this
service
    .getApi1()
    .then(function (api1Response) {
        // If I'm in here, I know that the request to service 1 is done
        return service
            .getApi2();
    }).then(function (api2Response) {
        // If I'm in here, I know that the request to service 2 is done
        console.log(api2Response);
    })
    .catch(function (err) {
        console.log("Something has gone wrong");
    });

你们两个getApi函数都应该看起来像这样的 ,他们做的主要事情是返回一些内容(如Promise)和.then()方法

function getApi1() {
    // This is returning a Promise
    return $http
        .get("some/resource/on/the/server.json")
        .then(function (response) {
            /*
             * Here I'm just peeling out the data from the response
             * because I don't actually care about the details of the
             * response, just the data
             */
            return response.data;
        });
}