background preloader

Promises

Facebook Twitter

JavaScript Promises for Dummies. Javascript Promises are not difficult. However, lots of people find it a little bit hard to understand at the beginning. Therefore, I would like to write down the way I understand promises, in a dummy way. Understanding Promises A Promise in short: "Imagine you are a kid. You don't know if you will get that phone until next week. That is a promise. Promise is pending: You don't know if you will get that phone until next week.Promise is resolved: Your mom really buy you a brand new phone.Promise is rejected: You don't get a new phone because your mom is not happy. Creating a Promise Let's convert this to JavaScript.

The code is quite expressive in itself. We have a boolean isMomHappy, to define if mom is happy.We have a promise willIGetNewPhone. New Promise( function (resolve, reject) { ... } ); What you need to remember is, when the result is successful, call resolve(your_success_value), if the result fails, call reject(your_fail_value) in your promise. Consuming Promises Demo: 9 Promising Promise Tips. Promises are great to work with!

9 Promising Promise Tips

Or so does your fellow developer at work says. This article would give you to the point no bullshit tips on how to improve your relationship with the Promises. Let me make the most important tip standout Yes! You can return a Promise inside a .then Also, the returned promise is automatically unwrapped in the next .then If you are familiar with the dot chaining style of javascript you would feel at home. In promises whenever you .then or .catch you are creating a new Promise. Let us look at an example: var statusProm = fetchServerStatus(); var promA = statusProm.then(r => (r.statusCode === 200 ? The relationship of above promises can be described neatly in a flow chart: The important thing to note here is that promA, promB and promC are all different promises but related. I like to think of .thening as a big massive plumbing where water will stop flowing to the children when the parent node malfunctions. Let us look at a redundant Promise constructor ☠️Wrong.

25. Promises for asynchronous programming. This chapter is an introduction to asynchronous programming via Promises in general and the ECMAScript 6 Promise API in particular.

25. Promises for asynchronous programming

The previous chapter explains the foundations of asynchronous programming in JavaScript. You can consult it whenever there is something that you don’t understand in this chapter. Learn ES6 (ECMAScript 2015) Learn ES6 (ECMAScript 2015) Using JavaScript Promises. LocalForage/localForage: □ Offline storage, improved. Wraps IndexedDB, WebSQL, or localStorage using a simple but powerful API. ES2015 Crash Course: Promises 101. Axios/axios: Promise based HTTP client for the browser and node.js.