Part 1 of Promises : because sometimes async functions just can’t be trusted!

I generally get a wide array of responses when I tell my dog to sit. Sometimes it happens instantly, other times it takes two or three tries, and sometimes he wont do it all, I think he needs a doggy boot-camp, but if I have a dog treat, the response is always executed when I expect. In the async world of Node, we can’t always tell when our async functions will sit, but we do have a useful treat to help tame these fickle creatures, insert Promises.

A promise is a way to simplify the potential callback nightmare created by Asynchronous code execution. Asyn code is amazing because it’s fast. Rather then waiting for a function to finish before I move to the next step, I can just move on and come back to it later. but wait,”what if the next step is dependent on the last step.” well darn that is a problem.

Question, your dad tell you that at some point in the day he will be over to pick up the dog for a lovely evening at the park, but you want to go out and watch a movie. what do you do?

You could ask what time he will be over and schedule your day appropriately, but in the world of internet traffic this level of coordination isn’t always possible. Your request to Facebook’s API will get handled when Facebook damn well pleases, and you will be grateful for it!

You could drop your plans and wait for him. This blocking approach works but it’s slow and causes you to miss a great movie. Well ok this is 2016, there is probably a decent quality cam on the internet already but that’s beside the point.

Finally, you could leave a key under the rug for him and go on about your day. This is the node style callback pattern at play. every async node function expects a callback, the key under the rug, as its last argument, and that callback will handle the result or error of the unpredictable parent. So callbacks solve the problem, great lets all go see that movie now. well not so fast, sometimes the results of a novel solution can have toxic side effects.

insert the pyramid of doom!

person1.call(function(){
console.log(1);
person2.call(function(){
console.log(2);
person3.call(function(){
console.log(3);
person4.call(function(){
console.log(4);
person5.call(function(){
console.log("finsihed")
});
});
});
});
});
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.