Thursday, March 17, 2016

Promises (ES6)

Thursday, March 17th 2016

What is a promise? 
Simply put, a promise is used in lieu of a value to allow code to be run asynchronously. Promises are important because they address an important issue and without them, websites and apps would take noticeably longer to run. The issue is that every time you make a request to a server, you have to wait for that server to respond, which can sometimes be slow (~1-2s). Meanwhile, there is all this other code to run that's all just waiting for this server response. So, instead, we can create a promise that refers to the value that we receive from the server some point later in the code so all of the other code can run. As a result, promises allow us to run code asynchronously thereby making our websites and apps much faster. Below is a flow chart explaining the process that promises go through.



So we start out with creating a promise (there are multiple modules for promises in es5, but thankfully promises are native to es6). Once we have encapsulated what code we want to run within the promise, we can then run code asynchronously while waiting for that promise to be settled (either fulfilled (success) or rejected (error)). Once it's settled, the promise is returned and the code moves on. (An important note, returning the promise typically refers to the value returned, not repeating another Promise Constructor).

References:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
http://stackoverflow.com/questions/22539815/arent-promises-just-callbacks
http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call?lq=1

No comments:

Post a Comment