如何使用回调重构链式 $http 调用和库调用

How to refactor chained $http calls and library call with callback

我的代码类似于以下片段:

$http({
    method: "GET",
    url: "/path/to/route?id=" + id
})
.then(function (response) {
    var data = response.data;

    var summary = service.doSomething(data, function (error, result, response) {
        if (error) {
            handleError();
            return;
        }

        $http({
            method: "POST",
            url: "path/to/another/route?key=" + data.key
        })
        .then(function () {
            // do stuff...
        });
    });

    summary.on("status", function () {
        // do stuff...
    });
})
.catch(function () {
    handleError();
});

有没有一种方法可以重构这样的东西,使代码不嵌套?本质上,我有三个请求,它们都依赖于它们的前任获得的值。有帮助吗?

将基于 API 的回调转换为承诺:

function doSomethingPromise(data) {
    var deferred = $q.defer();
    service.doSomething(data, function (error, result, response) {
    if (error) {
        deferred.reject(error);
    } else {
        deferred.resolve({result: result, response: response});
    };
    return deferred.promise;
}