Promises provide a well-defined interface for interacting with an object that represents the result of an action that is performed asynchronously, and may or may not be finished at any given point in time.
Analogy: You want to eat a Taco at TacoBell. You give your order and pay at the cashier's desk. The cashier gives you a receipt and order number. You wait for your turn and you are called when the order is ready.
Object: The receipt/order number. It's an assurance you'll get your food.
Result of action: You getting your food
Async: Food takes time to prepare, they take other orders in the meantime.
step1(function (value1) {
step2(value1, function(value2) {
step3(value2, function(value3) {
step4(value3, function(value4) {
// Do something with value4
});
});
});
});
pStep1()
.then(pStep2) // pStep2 gets called with the value returned by pStep1
.then(pStep3) // similar thing happens here
.then(function(value4) {
// do something with value4 here,
// which is the value returned by pStep3
})
.fail(function(err) {
// handle error here
})
.finally(function() {
// this is called in both cases
});
function oneZingerPlease(customFillings) {
return Q.Promise(function(resolve, reject, notify) {
var request = new zingerRequest(customFillings);
request.onload = function() {
if (request.status === 200) {
resolve(request.yummyZinger);
} else {
reject("Chef is feeling sad.");
}
}
request.onerror = function(err) {
reject("Cant make burger because", err);
}
request.onprogress = function(event) {
notify(event.loaded / event.total);
}
});
}
function oneTacoPlease(customFillings) {
var request = new tacoRequest(customFillings);
var deferred = Q.defer();
request.onload = function() {
if (request.status === 200) {
deferred.resolve(request.yummyTaco);
} else {
deferred.reject("Chef is feeling sad.");
}
}
request.onerror = function(err) {
deferred.reject("Cant make taco because", err);
}
request.onprogress = function(event) {
deferred.notify(event.loaded / event.total);
}
return deferred.promise;
}