我的代码类似于以下代码段:
$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();
});
是否有一种方法可以重构这样的东西,使得代码不会嵌套?本质上,我有三个请求,这三个请求均取决于其前任获得的值。帮助吗?
答案 0 :(得分:2)
将基于回调的API转换为Promise:
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;
}