有谁知道一些好的资源/书籍,我可以在其中找到如何处理多个异步请求?
让我们考虑下面的代码:
Payment.createToken = function(data) {
var data = data;
apiCall("POST", "api/createToken", data, function(success, response) {
if (success) {
data.token = response.id;
// If there's coupon code passed in data object, check it's validity, else send payment request
if (data.coupon) {
// Check if coupon is valid
Payment.verifyCoupon(data);
} else {
// Send payment request
Payment.chargePlan(data);
}
} else {
// Handle error
}
});
};
Payment.verifyCoupon = function(data) {
var data = data;
apiCall("POST", "/api/checkCoupon", data, function(success, response) {
if (success) {
Payment.chargePlan(data);
} else {
// Handle error
}
});
};
Payment.chargePlan = function(data) {
apiCall("POST", "/api/chargePlan", data, function(success, response) {
if (success) {
Payment.changeUserType(data);
} else {
// Handle error
}
});
};
Payment.changeUserType = function(data, response) {
apiCall("PUT", "api/users/", data, function(success, response) {
if (success) {
// User type changed successfully
} else {
// Handle error
}
});
};
如您所见,它很长,有 4 个步骤流程。我应该如何正确处理错误等?让我们考虑到这些调用应该尽可能地可重用。