有誰知道一些很好的資源/書籍,我可以找到如何處理多個異步請求?如何正確處理多個異步請求?
讓我們來看下面的代碼:
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
}
});
};
正如你可以看到,它的長,四步流程。我該如何妥善處理錯誤等?我們要考慮到這些調用應儘可能可重用。
使用[Promises](http://wiki.commonjs.org/wiki/Promises) – Bergi