Sunday, November 25, 2018

ECMAScript 6 Chaining Promises



I'm trying to chain promises, but the second one doesn't call the resolve function. What do I do wrong?




function getCustomers(){

let promise = new Promise(
function (resolve, reject){

console.log("Getting customers");
// Emulate an async server call here
setTimeout(function(){
var success = true;
if (success){
resolve( "John Smith"); // got the customer
}else{
reject("Can't get customers");
}
},1000);

}
);
return promise;
}

function getOrders(customer){

let promise = new Promise(
function (resolve, reject){

console.log("Getting orders");
// Emulate an async server call here
setTimeout(function(){
var success = true;
if (success){
resolve( "Order 123"); // got the order
}else{
reject("Can't get orders");
}
},1000);

}
);
return promise;
}

getCustomers()
.then((cust) => getOrders(cust))
.catch((err) => console.log(err));
console.log("Chained getCustomers and getOrders. Waiting for results");



The code prints "Getting orders" from the second function, but doesn't print "Order 123":



Getting customers
Chained getCustomers and getOrders. Waiting for results
Getting orders



Update. I wanted to insert the print on the console between chained methods that return promises. I guess something like this is not possible:




getCustomers()
.then((cust) => console.log(cust)) //Can't print between chained promises?
.then((cust) => getOrders(cust))
.then((order) => console.log(order))
.catch((err) => console.error(err));

Answer



You want to chain a success handler (for your resolve result "Order 123"), not an error handler. So use then instead of catch :-)



getCustomers()
.then(getOrders)
.then((orders) => console.log(orders))
.catch((err) => console.error(err));


None of the promises was rejected, so the console.log(err) in your code was never called.




I wanted to insert the print on the console between chained methods that return promises. I guess something like this is not possible:



getCustomers()
.then((cust) => console.log(cust)) //Can't print between chained promises?
.then((cust) => getOrders(cust))



Yes it is possible, but you are intercepting a chain here. So the second then callback actually is not called with cust, but with the result of the first then callback - and console.log returns undefined, with which getOrders will get some problems.



You'd either do



var customers = getCustomers();
customers.then(console.log);
customers.then(getOrders).then((orders) => …)


or simpler just



getCustomers()
.then((cust) => { console.log(cust); return cust; })
.then(getOrders)
.then((orders) => …)

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...