5 ways to use JavaScript promises
Briefly

5 ways to use JavaScript promises
"Promises are a central mechanism for handling asynchronous code in JavaScript. You will find them in many JavaScript libraries and frameworks, where they're used to manage the results of an action. The fetch() API is one example of promises at work. As a developer, you might not be familiar with creating and using promises outside of an existing product, but it's surprisingly simple. Learning how to create promises will help you understand how libraries use them."
"In this code, we define a fetchData() function that returns a Promise. We call the method and hold the Promise in the promise variable. Then we use the Promise.then() method to deal with the results. The essence of this example is that the fetchData() call happens immediately in the code flow, whereas the callback passed into then() only happens after the asynchronous operation is complete."
Promises represent objects that encapsulate the eventual result of an asynchronous operation. A Promise is created by calling new Promise and supplying a function that receives resolve and reject callbacks. Calling resolve signals successful completion and passes a value; calling reject signals failure. The provided example simulates a network call with setTimeout and resolves a string after two seconds. Code consuming the Promise uses then() to register a callback that runs after the asynchronous operation completes. Calling the function that returns the Promise executes immediately, while the then() callback runs later when resolve is invoked. Promises enable clearer asynchronous control flow and error handling.
Read at InfoWorld
Unable to calculate read time
[
|
]