When JS deals with asynchronous, promise deals with 'Callback hell'
Without Promise
isBusHere(function(isBusHereResult) {
isBusStop(function(isBusStopResult) {
isDoorOpen(function(isDoorOpenResult) {
findWallet(function(findWalletResult) {
findCard(function(findCardResult) {
payBusFare(function(payBusFareResult) {
// pay success
}, failureCallback);
}, failureCallback);
}, failureCallback);
}, failureCallback);
}, failureCallback);
}, failureCallback);
With promise
isBusHere().then(function(isBusHereResult) {
return isBusStop(isBusHereResult)
}).then(function(isBusStopResult) {
return isDoorOpen(isDoorOpenResult)
}).then(function(isDoorOpenResult) {
return findWallet(findWalletResult)
}).then(function(findWalletResult) {
return findCard(findCardResult)
}).then(function(findCardResult) {
return payBusFare(payBusFareResult)
}).catch(failureCallback);
With arrow function (to look better)
isBusHere()
.then(isBusStopResult => isBusStop(isBusStopResult))
.then(isDoorOpenResult => isDoorOpen(isDoorOpenResult))
.then(findWalletResult => findWallet(findWalletResult))
.then(findCardResult => findCard(findCardResult))
.then(payBusFareResult => payBusFare(payBusFareResult))
.catch(failureCallback);
const promise1 = new Promise((resolve, reject) => {});
console.log(promise1); // Promise { <pending> }
const promise2 = new Promise((resolve, reject) => {
resolve();
});
console.log(promise2) // Promise { undefined }
const promise3 = new Promise((resolve, reject) => {
//reject();
});
console.log(promise3) // Promise { <rejected> undefined }