JavaScript for Li...
Follow
Find tag "promises"
266.9K views | +162 today
JavaScript for Line of Business Applications
Keeping track of current JavaScript Frameworks that help design your clientside Business Logic Layers.
Curated by Jan Hesse
Beam to my Inbox:
Your new post is loading...
Your new post is loading...
Scoop.it!

Cancelling Long Promise Chains

My previous introduction to promises left out a common case: cancelling a chain of promise. Ideally, this is something you won't have to do too often; but for the one or two times when you run into it, here's one solution to handle it.

First though, the problem. Pretend you have a chain of promises, this could be a controller that has to go through multiple steps and transformation...


more...
No comment yet.
Scoop.it!

Using Resolve In AngularJS Routes

Using Resolve In AngularJS Routes | JavaScript for Line of Business Applications | Scoop.it

In a previous post about testing I mentioned that route resolves can make authoring unit tests for a controller easier. Resolves can also help the user experience.

A resolve is a property you can attach to a route in both ngRoute and the more robust UI router. A resolve contains one or more promises that must resolve successfully before the route will change. This means you can wait for data to become available before showing a view, and simplify the initialization of the model inside a controller because the initial data is given to the controller instead of the controller needing to go out and fetch the data.

As an example, let’s use the following simple service which uses $q to simulate the async work required to fetch some data.

more...
No comment yet.
Scoop.it!

Understanding Javascript Promises

Learning promises is an interesting process. Like many tools, there are common pitfalls to get stuck on. What makes promises somewhat unique is that it tends to be obvious that you're doing it wrong. Why? Promises are designed to solve a clear and well-understood problem: nested callbacks. As you start to use them however, you're code isn't that different. Obviously there's something you don't grok, but what?

The example that I'm going to walk through is a login. This involves:

1. Opening our connection
2. Getting the user's row from the DB based on email
3. Comparing the passwords
4. Updating the DB with a `token`
5. Releasing our connection
6. Returning the user data and token

more...
No comment yet.
Scoop.it!

Promise Anti-patterns

Promises are very simple once you get your head around them, but there are a few gotchas that can leave you with your head scratching. Here are a few that got me.

* Nested Promises
* The Broken Chain
* The Collection Kerfuffle
* The Ghost Promise
* The Overly Keen Error Handler
* The Forgotten Promise


more...
No comment yet.
Scoop.it!

JavaScript Promises: A Journey To The “Promise Land”

JavaScript Promises: A Journey To The “Promise Land” | JavaScript for Line of Business Applications | Scoop.it

Promises certainly aren’t the holy grail of asynchronous flow control in JavaScript. There are no silver bullets, after all. Promises are a tremendously important concept, and one that you need to understand, though. They’ve been around for a few years, have gone through various standards and APIs and are finally being added to JavaScript, proper. There are countless resources around the web these days, showing how promises work and what you can do with them. But in all this, it’s easy to get a bit lost. So I want to take you down a short journey – one that I’ve already travelled and documented fairly well. But here, I’ll summarize my journey of re-inventing promises (by accident), learning what they are and how I came to use them on a daily basis, for a while.

more...
No comment yet.
Scoop.it!

Replacing callbacks with ES6 Generators

Replacing callbacks with ES6 Generators | JavaScript for Line of Business Applications | Scoop.it

In this article we’re going to go step-by-step. We’ll progressively modify a toy callback-based example towards a generator-based solution. The goal is for you to understand how the entire process works, from end to end.

Generators are a new concept in JavaScript, but not in programming. You might have used them in other languages like Python. If not, have no fear, we’re going to do a gentle intro.

Generators in ES6 are declared like functions, except they have an asterisk: function* ticketGenerator() {}

When you want a generator to provide a value and then pause you use the yield keyword. yield is like return in that it hands back a value, except the function pauses after yield is called.

more...
No comment yet.
Scoop.it!

Managing Node.js Callback Hell with Promises, Generators and Other Approaches

Managing Node.js Callback Hell with Promises, Generators and Other Approaches | JavaScript for Line of Business Applications | Scoop.it

Callback hell is subjective, as heavily nested code can be perfectly fine sometimes. Asynchronous code is hellish when it becomes overly complex to manage the flow. A good question to see how much “hell” you are in is: how much refactoring pain would I endure if doAsync2 happened before doAsync1?The goal isn’t about removing levels of indentation but rather writing modular (and testable!) code that is easy to reason about and resilient.

In this article, we will write a module using a number of tools and libraries to show how control flow can work. We’ll even look at an up and coming solution made possible by the next version of Node.

Let’s say we want to write a module that finds the largest file within a directory.

* A nested approach
* A modular approach
* An async approach
* A promises approach
* A generators approach


more...
No comment yet.
Scoop.it!

Six Things You Might Not Know About Promises

Promises are a simple concept, and even if you haven’t had a chance to use them, you may have already read up on them. They are a valuable construct that enables asynchronous code to be structured in a more readable fasion, rather than as a mess of nested anonymous functions. This article touches on six things that you might not know about promises.

Before diving into the list, here is a quick reminder of what JavaScript promises look like...

 

1. then() Returns a Forked Promise
2. Callbacks Should Pass Results
3. Only Exceptions From Previous Levels are Caught
4. Errors Can Be Recovered From
5. Promises Can Be Paused
6. Resolved Promises Don’t Execute Immediately

more...
No comment yet.
Scoop.it!

Promises instead of callbacks in EmberJS

A few weeks ago I built up a very simple identity map to get rid of a bug in highlighting active links. I introduced promises in order to leverage the fact that Ember.js blocks in model hooks until the model is resolved (or rejected).

In this post, I am taking a step back, and converting all the ajax calls that fetch data from and store data to the backend to use promises. I am also going to extract the most basic adapter that exists, just to do away with the repetition in the XHR calls. Once I have these in place, I will able able to build nice features on top of that.

more...
No comment yet.
Scoop.it!

Callbacks, Promises, Signals and Events

Callbacks, Promises, Signals and Events | JavaScript for Line of Business Applications | Scoop.it

Sometimes I get involved in discussions on twitter and Facebook related to development. This week I ended up sending a link to an old(ish) twitter thread explaining when to favor Promises/Callbacks and when to use Signals/Events for asynchronous operations. I think this topic deserves further explanation.

more...
No comment yet.
Scoop.it!

The AngularJs Promise Anti-Pattern That Makes Me Cry

Asynchronous interactions in AngularJs are built on promises. A lot has been said on the subject of promises already. So I won’t cover their purpose extensively here. Long story short, use them.

Sadly enough, the reasons for using promises are still widely misunderstood. One pattern, in particular, I still see quite often with new users of promises. I don’t have a cool name for it, but if I did, it would be: “The AngularJs promise anti-pattern that makes me cry.” But that’s just because I’m over-dramatic.

In general, I’ve seen this pattern in the following form...

more...
No comment yet.
Scoop.it!

Managing the Asynchronous Nature of Node.js

Managing the Asynchronous Nature of Node.js | JavaScript for Line of Business Applications | Scoop.it

Node.js allows you to create apps fast and easily. But due to its asynchronous nature, it may be hard to write readable and manageable code. In this article I’ll show you a few tips on how to achieve that.


Solution 1: Callback Naming and Modularization
Solution 2: Promises
Solution 3: Step Library

 

As you can see, the asynchronous nature of Node.js can be managed and the callback hell can be avoided. I’m personally using the modularization approach, because I like to have my code well structured. I hope these tips will help you to write your code more readable and debug your scripts easier.

more...
No comment yet.
Scoop.it!

JavaScript Promises: There and back again

JavaScript Promises: There and back again | JavaScript for Line of Business Applications | Scoop.it
What's all the fuss about?

JavaScript is single threaded, meaning that two bits of script cannot run at the same time, they have to run one after another. In browsers, JavaScript shares a thread with a load of other stuff. What that stuff is differs from browser to browser, but typically JavaScript is in the same queue as painting, updating styles, and handling user actions (such as highlighting text and interacting with form controls). Activity in one of these things delays the others.

 

* What's all the fuss about?
* Events aren't always the best way
* Promise terminology
* Promises arrive in JavaScript!
* Browser support & polyfill
* Compatibility with other libraries
* Complex async code made easier
* Promisifying XMLHttpRequest
* Chaining
* Error handling
* Parallelism and sequencing - Getting the best of both
* Promise API Reference

more...
No comment yet.
Scoop.it!

Write Better JavaScript with Promises

Write Better JavaScript with Promises | JavaScript for Line of Business Applications | Scoop.it

You've probably heard the talk around the water cooler about how promises are the future. All of the cool kids are using them, but you don't see what makes them so special. Can't you just use a callback? What's the big deal? In this article, we'll look at what promises are and how you can use them to write better JavaScript.

more...
No comment yet.
Scoop.it!

AngularJS Promises - The Definitive Guide

AngularJS Promises - The Definitive Guide | JavaScript for Line of Business Applications | Scoop.it

Promises are a core feature of AngularJS - whether you understand them or not, if you use AngularJS you've almost certainly been using them for a while.

In this post I'm going to explain what promises are, how they work, where they're used and finally how to use them effectively.

Once we've got the core understanding of promises, we'll look at some more advanced functionality - chaining and resolving promises when routing.


Contents:
* What are Promises?
* How do Promises Work?
* A Real World Example
* Promises - Success, Error, Then
* Advanced Promises - Chaining
* Advanced Promises - Routing
* The Future of Promises
* Wrapping Up

more...
No comment yet.
Scoop.it!

Promises and Error Handling

Promises and Error Handling | JavaScript for Line of Business Applications | Scoop.it

We’ve standardized on using promises to manage most of the asynchronous interactions in our JavaScript codebase. In addition to really enjoying the extra expressiveness and aggregation possibilities offered by promises, we’re benefitting greatly from richer error handling. We’ve had some surprises though, and this post explains some things which caught us out and some guidelines we’re following to avoid similar situations in future.

We use the excellent when.js library, however this post should be relevant no matter what implementation you’re using.

more...
No comment yet.
Scoop.it!

Thoughts On JavaScript Generators

Thoughts On JavaScript Generators | JavaScript for Line of Business Applications | Scoop.it

When anyone complains about the pain of callback functions, the usual recommendation is to use promises. Promises have been around for a number of years and there are a variety of promise libraries available for both Node and client scripting environments, with Q being a popular package for node.

Promises are useful, particularly when they destroy a pyramid of doom. But promises can’t un-butcher the code sliced into functions to meet the demands of an asynch API. Also, promises require shims to transform a function expecting a callback into a function returning a promise, which is what Q.nfcall will do in the following code.

ECMAScript 6 (a.k.a Harmony) introduces the yield keyword. Anyone with some programming experience in C# or Python (and a number of other languages, except Ruby) will already be familiar with how yield can suspend execution of a function and return control (and a value) to the caller. At some later point, execution can return to the point just after yield occurred. In ES6, functions using the yield keyword are known as generator functions and have a special syntax (function*), as the following code demonstrates...

more...
No comment yet.
Scoop.it!

Flattening Promise Chains

Flattening Promise Chains | JavaScript for Line of Business Applications | Scoop.it
Managing asynchronous activity is Javascript is almost easy when you using Promise chains.

Promises allow developers to easily attach 1x-only notifications of response to any asynchronous request/action. Promises also enable two (2) other very important things. We can:

  • Transform the responses before subsequent handlers (in the chain) are notified of the response.
  • Use the response to invoke more async requests (which could generate more promises).

But even more important than the features above, Promises support easy chaining of custom activity or computations. Managing sequences or chains of asynchronous activity can be a very difficult and complex effort. Promise chains are amazing and provide means to easily build sequences of asynchronous requests or asynchronous activity.

more...
No comment yet.
Scoop.it!

JavaScript Promises ... In Wicked Detail

JavaScript Promises ... In Wicked Detail | JavaScript for Line of Business Applications | Scoop.it

I’ve been using Promises in my JavaScript code for a while now. They can be a little brain bending at first. I now use them pretty effectively, but when it came down to it, I didn’t fully understand how they work. This article is my resolution to that. If you stick around until the end, you should understand Promises well too.


We will be incrementally creating a Promise implementation that by the end will mostly meet the Promise/A+ spec, and understand how promises meet the needs of asynchronous programming along the way. This article assumes you already have some familiarity with Promises. If you don’t, promisejs.org is a good site to checkout.


Why bother to understand Promises to this level of detail? Really understanding how something works can increase your ability to take advantage of it, and debug it more successfully when things go wrong. I was inspired to write this article when a coworker and I got stumped on a tricky Promise scenario. Had I known then what I know now, we wouldn’t have gotten stumped.

more...
No comment yet.
Scoop.it!

Cleaning up promises with yield

Last time we cleaned up callback hell with yield but callbacks in the design which I was talking about are not all that common these days, especially if you're working in the browser. When you're in the browser there's a good chance you're going to be working with Promises, and more accurately Promise/A+.

If you're unfamiliar with Promises, it's a specification which is states that you have an object which exposes a then method which will either fulfill or reject some operation. You've probably come across it with AJAX requests...

more...
No comment yet.
Scoop.it!

Pragmatic JavaScript

So you've been toying around with JavaScript. You have a basic feel for the language but don't quiet feel productive, yet. If so, this talk is for you. We'll peel away the abstractions, libraries, and frameworks to uncover the more interesting fundamentals of JavaScript. Specifically, we'll delve into the following: 
* Prototypal inheritance (and alternatives to classical inheritance) 
* Closures 
* Scope versus context and this 
* Public vs privileged vs private variables 
* Modules 
* Promises / Futures 
* Recent improvements from EcmaScript 5 and 6 
* Functional programming strategies 
* Documentation using JSDoc 
* Testing strategies 
* and more!

more...
No comment yet.
Scoop.it!

Asynchronous Control Flow with jQuery.Deferred

Asynchronous Control Flow with jQuery.Deferred | JavaScript for Line of Business Applications | Scoop.it
How to adapt callback structures to callback queues using deferred objects (promises).

Zumba® Tech is a big fan of javascript promises; they free our code from callback hell by allowing us to use a more elegant and abstract structure. With promises, asynchronous control flow becomes intuitive (first a and b, then c) and fun. Today, I’ll show you how to adapt a third party library that uses callbacks to a promise interface.

more...
No comment yet.
Scoop.it!

Taming node.js callbacks with caolan/async

Lately I've started dabbling in node.js development. I am developing a rest service api for a windows phone 8 application. Soon enough I noticed that my request handlers have too many nested callbacks.

My requirements were that it must be easy to pass the result of one function to the next one, no weird wrapping functions in other functions return deferreds and promises and whatever.

After googling around a bit, i found a few async libraries built for javascript like caolan/async, q and many others. I couldn't wrap my head around how they work, i couldn't find any real life eamples only useless tutorial examples.

So after a while i decide to use https://github.com/caolan/async#waterfall. Why? You can use any function with it, it is easy to pass the results to the next function and no wrapping non-promise functions. And I've been already using it's array manipulation functions already.

So what did it bring me? A few examples...

more...
No comment yet.
Scoop.it!

An Overview of JavaScript Promises

An Overview of JavaScript Promises | JavaScript for Line of Business Applications | Scoop.it

Well, this has come like a Christmas gift to all JavaScript developers. You will be glad to know that Promises are now a part of standard JavaScript. Chrome 32 beta has already implemented the basic Promise API. The concept of Promises is not new to web development. Many of us have already used Promises in the form of several JS libraries such as Q, when, RSVP.js, etc. Even jQuery has something called Deferred which is similar to a Promise. But having native support for Promises in JavaScript is really amazing. This tutorial will cover the basics of Promises and show how you can leverage them in your JS development.

Jan Hesse's insight:

http://www.sitepoint.com/deeper-dive-javascript-promises/

more...
No comment yet.
Scoop.it!

JavaScript: Async Promise "while loop"

JavaScript: Async Promise "while loop" | JavaScript for Line of Business Applications | Scoop.it

This is a solution to the situation where you have an asynchronous task you want to perform over and over again, in a non-blocking fashion, stopping when some condition is met.

To set the stage, I’ll be using the Bluebird Promise library, the best Promise library I’ve used.

First, we’ll construct the Promise function which will do the looping:...

more...
No comment yet.