Promises

We will cover promises in greater detail when we make use of them in Chapter 12Integrating Backend Data Services, and so I'll defer the code until that time. The reason is thatshowing a really good real-world example of a promise, so that it's not contrived, takes quite a bit of code, since there needs to be asynchronous code that is called. So, I promise to have real-world promises later on in the book. However, we can at least look at a definition so that you know what they are.

When you call a function that may take a long time to return a result or to complete its task, and you don't want to delay the execution of your program, you can call that function asynchronously. This means that your code will continue on to the next line after it calls the function on the previous line asynchronously. If you don't call it asynchronously, your program's execution will stop and wait for the function you last called to return from what it was doing, such as reading a bunch of records from a database.

 There are a few different ways to call a function asynchronously. The most common way to call a function asynchronously is to use callbacks. A callback is a function that you pass to the function that you call asynchronously so it can then call that function when it has completed its work. That's how callbacks got their name; the function you called calls you back when it's done.

Promises are another mechanism we can use to program asynchronously. Although Promises made things a little more manageable, writing good asynchronous code in JavaScript is often still notoriously difficult. Because of this fact, people started writing JavaScript libraries to try and make asynchronous code easier to write. There are several out there. One library that saved my sanity is called Async.

All this being said, I still have not given you a definition of Promises, so here it is: a Promise is a proxy for a value that is not yet known; it's like a placeholder for the value that will eventually come back from a function that was called asynchronously. This construct allows asynchronous functions to immediately return a value as if it was a synchronous method. The initial value that is returned is a Promise, and the Promise will eventually be replaced by the value that comes back from the called function once it has completed its work.

I know this may be a lot to get your head around, but when we write our code in Chapter 12Integrating Backend Data Services, you will understand Promises. That's a promise, pun intended.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.218.230