原文:http://blog.mediumequalsmessage.com/promise-deferred-objects-in-javascript-pt1-theory-and-semantics

Introduction

In the not too distant past the primary tool available to JavaScript programmers for handling asynchronous events was the callback.

A callback is a piece of executable code that is passed as an argument to other code, which is expected to call back ( execute ) the argument at some convenient time
— Wikipedia

In other words, a function can be passed as an argument to another function to be executed when it is called.

There’s nothing inherently wrong with callbacks, but depending on which environment we are programming in there are a number of options available for managing asynchronous events. In this post my goal is to examine one set of available tools: promise objects and deferred objects. In part I, we will cover theory and semantics and in part 2 we will look at the use.

One of the keys to effectively working with asynchronous events in JavaScript is understanding that the program continues execution even when it doesn’t have the value it needs for work that is in progress. Dealing with as yet unknown values from unfinished work can make working with asynchronous events in JavaScript challenging — especially when you’re first getting started.

A classic example of this would be an XMLHttpRequest ( Ajax ). Imagine we want to:

  • make an Ajax request to get some data
  • immediately do something with that data, and then
  • do other things

In our program we initiate our Ajax request. The request is made but unlike with synchronous events, execution of our program isn’t stopped while the server is responding, instead the program continues running. By the time we get the response data from our Ajax request, the program has already finished execution.

Promises & Deferreds: What are they?

Promises are a programming construct that have been around since 1976. In short:

  • a promise represents a value that is not yet known
  • a deferred represents work that is not yet finished

Considered from a high level, promises in JavaScript give us the ability to write asynchronous code in a parallel manner to synchronous code. Let’s start with a diagram to get an overview of the big picture before diving into the specifics.

A promise is a placeholder for a result which is initially unknown while a deferred represents the computation that results in the value. Every deferred has a promise which functions as a proxy for the future result. While a promise is a value returned by an asynchronous function, a deferred can be resolved or rejected by it’s caller which separates the promise from the resolver. The promise itself can be given to any number of consumers and each will observe the resolution independently meanwhile the resolver / deferred can be given to any number of producers and the promise will be resolved by the one that first resolves it. From a semantic perspective this means that instead of calling a function ( callback), we are able to return a value ( promise ).

Promises According to the Promise/A Proposal

The Promises /A Proposal suggests the following standard behavior and API regardless of implementation details.

A promise:

  • Represents the eventual value returned from the single completion of an operation
  • may be in one of 3 states: unfulfilled, fulfilled and failed and may only move from unfulfilled to either fulfilled or failed
  • has a function as a value for the property “then” ( which must return a promise)
  • Adds a fulfilledHandler, errorHandler, and progressHandler to be called for completion of a promise.

    then(fulfilledHandler, errorHandler, progressHandler)
  • The value that is returned from the callback handler is the fulfillment value for the returned promise

  • promise’s value MUST not be changed (avoids side effects from listeners creating unanticipated behavior)

In other words, stripping out some of the nuances for a moment:

A promise serves as a proxy for a future value, has 3 possible states and needs to have a function which adds handlers for it’s states: fulfilledHandler, errorHandler and progressHandler ( optional ) and returns a new promise ( to allow chaining ) which will be resolved / rejected when the handler finishes executing.

The states and return value of a promise

A promise has 3 possible states: unfulfilled, fulfilled and failed.

  • unfulfilled: since a promise is a proxy for an unknown value it starts in an unfulfilled state
  • fulfilled: the promise is filled with the value it was waiting for
  • failed: if the promise was returned an exception, it is in the failed state.

A promise may only move from unfulfilled to either fulfilled or failed. Upon resolution or rejection, any observers are notified and passed the promise / value. Once the promise has been resolved or rejected neither it’s state or the resulting value can be modified.

Here is an example of what this looks like:

// Promise to be filled with future value
var futureValue = new Promise(); // .then() will return a new promise
var anotherFutureValue = futureValue.then(); // Promise state handlers ( must be a function ).
// The returned value of the fulfilled / failed handler will be the value of the promise.
futureValue.then({ // Called if/when the promise is fulfilled
fulfilledHandler: function() {}, // Called if/when the promise fails
errorHandler: function() {}, // Called for progress events (not all implementations of promises have this)
progressHandler: function() {}
});

Implementation differences & Performance

When choosing a promise library, there are a number of considerations to take into account. Not all implementations are created equal. They can differ in regards to what utilities are offered by the API, performance and even in behaviour.

Since the Promise/A proposal only outlines a proposal for the behaviour of promises and not implementation specifics, varying promise libraries have differing sets of features. All Promise/A compliant implementations have a .then() function but also have varying features in their API. Additionally, they are still able to exchange promises with each other. jQuery is the noticeable exception to the rule because its implementation of promises is not fully Promise/A compliant. The impact of this decision is documented here and discussed here. In Promise/A compliant libraries, a thrown exception is translated into a rejection and the errorHandler() is called with the exception. In jQuery’s implementation an uncaught exception will hault the program’s execution. As a result of the differing implementation, there are interoperability problems if working with libraries which return or expect Promise/A compliant promises.

One solution to this problem is to convert jQuery promises into Promise/A compliant promises with another promise library and then use the API from the compliant library.

For example:

when($.ajax()).then()

When reading through jQuery’s decision to stick with their implementation of promises, a mention of performance considerations piqued my curiosity and I decided to do a quick performance test. I used Benchmark.js and tested the results of creating and resolving a deferred object with a success handler in .then().

The results:

jQuery 91.6kb When.js 1.04kb Q.js 8.74kb
9,979 ops/sec ±10.22% 96,225 ops/sec ±10.10% 2,385 ops/sec ±3.42%

Note: minified with Closure compiler, not gzipped

After running these tests, I discovered a much more in-depth test-suite of promise libraries which reveals similar overall results.

The differences in performance may be negligible in a real application but in my Benchmark.js tests, when.js comes out as a clear winner. This combination of speed and the small size of the library make when.js a great choice when considering performance in the equation.

Clearly there are tradeoffs to consider when choosing a promise library. The answer to which library you should use depends on your specific use case and the needs of your project. Some implementations to start exploring are:

  • When.js: Fast, lightweight implementation that has a number of useful utilities and as of v2.0 has full support for asynchronous resolution.
  • Q.js: Runs in the browser or Node.js, offers a robust API and is fully Promise/A compliant.
  • RSVP: Barebones implementation that is fully Promise/A compliant.
  • jQuery: Not Promise/A compliant but is widely used. If you are already using jQuery in your project it’s easy to get started with and worth a look.

Conclusion

Promises provide the JavaScript developer a tool for working with asynchronous events . Now that we’ve covered some of the specifics of what promise objects and deferred objects are and how they behave, we are ready to dive into the specifics of how to work with them. In part 2, we’ll take a closer look at using promises, some common gotcha’s and some specifics of the jQuery API. In the meantime, feel free to start a conversation on App.net or Hacker News.

Further Resources

Books

Articles

JSFiddle

Promise & Deferred objects in JavaScript Pt.1: Theory and Semantics.的更多相关文章

  1. Promise & Deferred Objects in JavaScript Pt.2: in Practice

    原文:http://blog.mediumequalsmessage.com/promise-deferred-objects-in-javascript-pt2-practical-use Intr ...

  2. based on Greenlets (via Eventlet and Gevent) fork 孙子worker 比较 gevent不是异步 协程原理 占位符 placeholder (Future, Promise, Deferred) 循环引擎 greenlet 没有显式调度的微线程,换言之 协程

    gevent GitHub - gevent/gevent: Coroutine-based concurrency library for Python https://github.com/gev ...

  3. A brief look at the Objects in JavaScript

    Objects  An object is a self-contained collection of data. This data comes in to forms:  properties ...

  4. Promise/Deferred

    [fydisk] 1.$.get('/api').success(onSuccess).error(onError).comlete(onComplete); 2.对同一事件加入多个Handler. ...

  5. 异步编程Promise/Deferred、多线程WebWorker

    长期以来JS都是以单线程的模式运行的,而JS又通常应用在操作用户界面和网络请求这些任务上.操作用户界面时不能进行耗时较长的操作否则会导致界面卡死,而网络请求和动画等就是耗时较长的操作.所以在JS中经常 ...

  6. Jquery AJAX如何使用Promise/Deferred实现顺序执行?

    有的时候有我有N个AJAX请求,第下个请求可能要依赖上个请求的返回值, 可以用 $.ajax("test1.php").then(function(data) { // data ...

  7. 细说Promise

    一.前言 JavaScript是单线程的,固,一次只能执行一个任务,当有一个任务耗时很长时,后面的任务就必须等待.那么,有什么办法,可以解决这类问题呢?(抛开WebWorker不谈),那就是让代码异步 ...

  8. javascript中的promise和deferred:实践(二)

    javascript中的promise和deferred:实践(二) 介绍: 在第一节呢,我花了大量的时间来介绍promises和deferreds的理论.现在呢,我们来看看jquery中的promi ...

  9. Javascript - Promise学习笔记

    最近工作轻松了点,想起了以前总是看到的一个单词promise,于是耐心下来学习了一下.   一:Promise是什么?为什么会有这个东西? 首先说明,Promise是为了解决javascript异步编 ...

随机推荐

  1. [转] Linux Daemon Writing HOWTO

    Linux Daemon Writing HOWTO Devin Watson v1.0, May 2004 This document shows how to write a daemon in ...

  2. c#基础学习(0626)之占位符、转义符

    占位符 使用方法:先挖个坑,再填个坑. 使用占位符需要注意的地方: 1.你挖了几个坑,就应该填几个坑,如果填多了,没效果,如果填少了,出现异常 异常是指:语法上没有任何错误,只不过再运行的期间,由于某 ...

  3. MVC 之HTML辅助方法

    顾名思义,HTML辅助方法(HTML Helper)就是用来辅助产生HTML之用,在开发View的时候一定会面对许多HTML标签,处理这些HTML的工作非常繁琐,为了降低View的复杂度,可以使用HT ...

  4. mysql 表支持事务的方法

    1.在mysql客户管,如:Navicate.SQLyog在导航面板中选择要转换为InnoDB存储引擎类型的数据库,例如选择db_yunping数据库.如下图所示: 2. 在查询窗口中输入 show ...

  5. Resharper 使用帮助-自动生成文件头

    VS2012 安装完resharper 后,在resharper选项中选择 Code Editing – File Header Text . 输入自定义的文件头格式.如果需要在文件头外层添加regi ...

  6. Hive,HANA可视化客户端工具

    目前市面上的Hive可视化客户端工具,大都是C/S模式的,安装使用都不是太方便,目前有一款基于WEB的可视化工具TreeSoft,通过浏览器就可以访问使用了,并且可以同时管理.维护.监控MySQL,O ...

  7. 注重结构、语义、用户体验的Tab选项卡

    效果如下图所示: HTML code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" &quo ...

  8. centos 删除文件和目录

    每次都记不住,发个文章记录一下.直接rm就可以了,不过要加两个参数-rf 即:rm -rf 目录名字-r 就是向下递归,不管有多少级目录,一并删除-f 就是直接强行删除,不作任何提示的意思 删除文件夹 ...

  9. [移动端WEB] 移动端input标签按钮为什么在苹果手机上还有一层白色?

    移动端input标签按钮为什么在苹果手机上还有一层白色? 解决办法:其实蛮简单的,就加一个属性就好了 input { outline:0px ; -webkit-appearance: none; } ...

  10. js时间与毫秒数互相转换(转)

    [1]js毫秒时间转换成日期时间   var oldTime = (new Date("2017/04/25 19:44:11")).getTime(); //得到毫秒数    / ...