Motivation

Consider the following synchronous JavaScript function to read a file and parse it as JSON. It is simple and easy to read, but you wouldn't want to use it in most applications as it is blocking. This means that while you are reading the file from disk (a slow operation) nothing else can happen.

function readJSONSync(filename) {
return JSON.parse(fs.readFileSync(filename, 'utf8'));
}

To make our application performant and responsive, we need to make all the operations that involve IO be asynchronous. The simplest way to do this would be to use a callback. However, a naive implementation will probably go wrong:

function readJSON(filename, callback){
fs.readFile(filename, 'utf8', function (err, res){
if (err) return callback(err);
callback(null, JSON.parse(res));
});
}
  • The extra callback parameter confuses our idea of what is input and what is the return value.
  • It doesn't work at all with control flow primitives.
  • It doesn't handle errors thrown by JSON.parse

We need to handle errors thrown by JSON.parse but we also need to be careful not to handle errors thrown by the callback function. By the time we've done all of this our code is a mess of error handling:

function readJSON(filename, callback){
fs.readFile(filename, 'utf8', function (err, res){
if (err) return callback(err);
try {
res = JSON.parse(res);
} catch (ex) {
return callback(ex);
}
callback(null, res);
});
}

Despite all this mess of error handling code, we are still left with the problem of the extra callback parameter hanging around. Promises help you naturally handle errors, and write cleaner code by not having callback parameters, and without modifying the underlying architecture (i.e. you can implement them in pure JavaScript and use them to wrap existing asynchronous operations).

What is a promise?

The core idea behind promises is that a promise represents the result of an asynchronous operation. A promise is in one of three different states:

  • pending - The initial state of a promise.
  • fulfilled - The state of a promise representing a successful operation.
  • rejected - The state of a promise representing a failed operation.

Once a promise is fulfilled or rejected, it is immutable (i.e. it can never change again).

Constructing a promise

Once all of the APIs return promises, it should be relatively rare that you need to construct one by hand. In the meantime, we need a way to polyfill existing APIs. For example:

function readFile(filename, enc){
return new Promise(function (fulfill, reject){
fs.readFile(filename, enc, function (err, res){
if (err) reject(err);
else fulfill(res);
});
});
}

We use new Promise to construct the promise. We give the constructor a factory function which does the actual work. This function is called immediately with two arguments. The first argument fulfills the promise and the second argument rejects the promise. Once the operation has completed, we call the appropriate function.

Awaiting a promise

In order to use a promise, we must somehow be able to wait for it to be fulfilled or rejected. The way to do this is using promise.done (see warning at the end of this section if attempting to run these samples).

With this in mind, it's easy to re-write our earlier readJSON function to use promises:

function readJSON(filename){
return new Promise(function (fulfill, reject){
readFile(filename, 'utf8').done(function (res){
try {
fulfill(JSON.parse(res));
} catch (ex) {
reject(ex);
}
}, reject);
});
}

This still has lots of error handling code (we'll see how we can improve on that in the next section) but it's a lot less error prone to write, and we no longer have a strange extra parameter.

Non Standard

Note that promise.done (used in the examples in this section) has not been standardised. It is supported by most major promise libraries though, and is useful both as a teaching aid and in production code. I recommend using it along with the following polyfill (minified / unminified): undefined

Transformation / Chaining

Following our example through, what we really want to do is transform the promise via another operation. In our case, this second operation is synchronous, but it might just as easily have been an asynchronous operation. Fortunately, promises have a (fully standardised, except jQuery) method for transforming promises and chaining operations.

Put simply, .then is to .done as .map is to .forEach. To put that another way, use .then whenever you're going to do something with the result (even if that's just waiting for it to finish) and use .done whenever you aren't planning on doing anything with the result.

Now we can re-write our original example as simply:

function readJSON(filename){
return readFile(filename, 'utf8').then(function (res){
return JSON.parse(res)
})
}

Since JSON.parse is just a function, we could re-write this as:

function readJSON(filename){
return readFile(filename, 'utf8').then(JSON.parse);
}

This is very close to the simple synchronous example we started out with.

Implementations / Polyfills

p Promises are useful both in node.js and the browser

jQuery

This feels like a good time to warn you that what jQuery calls a promise is in fact totally different to what everyone else calls a promise. jQuery's promises have a poorly thought out API that will likely just confuse you. Fortunately, instead of using jQuery's strange version of a promise, you can just convert it to a really simple standardised promise:

var jQueryPromise = $.ajax('/data.json');
var realPromise = Promise.resolve(jQueryPromise);
//now just use `realPromise` however you like.

Browser

Promises are currently only supported by a pretty small selection of browsers (see kangax compatibility tables). The good news is that they're extremely easy to polyfill (minified / unminified):

<script src="https://www.promisejs.org/polyfills/promise-7.0.4.min.js"></script>

None of the browsers currently support Promise.prototype.done so if you want to use that feature, and you are not including the polyfill above, you must at least include this polyfill (minified / unminified):

<script src="https://www.promisejs.org/polyfills/promise-done-7.0.4.min.js"></script>

Node.js

It's generally not seen as good practice to polyfill things in node.js. Instead, you're better off just requiring the library wherever you need it.

To install promise run:

npm install promise --save

Then you can load it into a local variable using require

var Promise = require('promise');

The "promise" library also provides a couple of really useful extensions for interacting with node.js

var readFile = Promise.denodeify(require('fs').readFile);
// now `readFile` will return a promise rather than
// expecting a callback function readJSON(filename, callback){
// If a callback is provided, call it with error as the
// first argument and result as the second argument,
// then return `undefined`. If no callback is provided,
// just return the promise.
return readFile(filename, 'utf8')
.then(JSON.parse)
.nodeify(callback);
}

Further Reading

Promise deeply lookup的更多相关文章

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

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

  2. Javascript - Promise学习笔记

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

  3. 路由的Resolve机制(需要了解promise)

    angular的resovle机制,实际上是应用了promise,在进入特定的路由之前给我们一个做预处理的机会 1.在进入这个路由之前先懒加载对应的 .js $stateProvider .state ...

  4. angular2系列教程(七)Injectable、Promise、Interface、使用服务

    今天我们要讲的ng2的service这个概念,和ng1一样,service通常用于发送http请求,但其实你可以在里面封装任何你想封装的方法,有时候控制器之间的通讯也是依靠service来完成的,让我 ...

  5. 闲话Promise机制

    Promise的诞生与Javascript中异步编程息息相关,js中异步编程主要指的是setTimout/setInterval.DOM事件机制.ajax,通过传入回调函数实现控制反转.异步编程为js ...

  6. 深入理解jQuery、Angular、node中的Promise

    最初遇到Promise是在jQuery中,在jQuery1.5版本中引入了Deferred Object,这个异步队列模块用于实现异步任务和回调函数的解耦.为ajax模块.队列模块.ready事件提供 ...

  7. Promise的前世今生和妙用技巧

    浏览器事件模型和回调机制 JavaScript作为单线程运行于浏览器之中,这是每本JavaScript教科书中都会被提到的.同时出于对UI线程操作的安全性考虑,JavaScript和UI线程也处于同一 ...

  8. JavaScript进阶之路——认识和使用Promise,重构你的Js代码

    一转眼,这2015年上半年就过去了,差不多一个月没有写博客了,"罪过罪过"啊~~.进入了七月份,也就意味着我们上半年苦逼的单身生活结束了,从此刻起,我们要打起十二分的精神,开始下半 ...

  9. SQL Server-聚焦移除Bookmark Lookup、RID Lookup、Key Lookup提高SQL查询性能(六)

    前言 前面几节都是讲的基础内容,本节我们讲讲索引性能优化,当对大数据进行处理时首先想到的就是索引,一旦遇到这样的问题则手忙脚乱,各种查资料,为何平常不扎实基本功呢,我们由浅入深,简短的内容,深入的理解 ...

随机推荐

  1. mysql: unknown variable 'character-set-client=utf8'

    在同事安装的MySQL服务器上(居然安装的是My-SQL 5.1.73的老旧版本),登录MySQL时遇到下面"mysql: unknown variable 'character-set-c ...

  2. Nagios学习实践系列——配置研究[监控当前服务器]

    其实上篇Nagios学习实践系列——基本安装篇只是安装了Nagios基本组件,虽然能够打开主页,但是如果不配置相关配置文件文件,那么左边菜单很多页面都打不开,相当于只是一个空壳子.接下来,我们来学习研 ...

  3. [AlwaysOn Availability Groups]DMV和系统目录视图

    DMV和系统目录视图 这里主要介绍AlwaysON的动态管理视图,可以用来监控和排查你的AG. 在AlwaysOn Dashboard,你可以简单的配置的GUI显示很多可用副本的DMV和可用数据库通过 ...

  4. PHP服务缓存优化之ZendOpcache、xcache、eAccelerator

    PHP服务缓存优化原理 Nginx 根据扩展名或者过滤规则将PHP程序请求传递给解析PHP的FCGI,也就是php-fpm进程 缓存操作码(opcode) Opcode,PHP编译后的中间文件,缓存给 ...

  5. 带你一步步的了解“C#事件”机制

    是什么 本文讨论类型中定义的最后一种成员:事件 定义了时间成员的类型允许类型通知其他对象发生了特定的事情. 具体的说,定义了时间成员的类型能提供以下功能: 方法能登记它对事件的关注 方法能注销它对事件 ...

  6. 《java JDK7 学习笔记》之对象封装

    1.构造函数实现对象初始化流程的封装.方法封装了操作对象的流程.java中还可以使用private封装对象私有数据成员.封装的目的主要就是隐藏对象细节,将对象当做黑箱子进行操作. 2.在java命名规 ...

  7. mysql5.7.1 zip版本安装记录

    很久没遇到使用mysql的项目了,今天下载了个,发现变了很多,搜索了下,发现按http://www.cnblogs.com/wenthink/p/MySQLInstall.html中提到的基本可以使用 ...

  8. openwrt 安装 ser2net 配置

    //--- openwrt中的ipk应用 opkg install /tmp/ser2net_2.7-2_brcm63xx.ipk 看到安装成功的信息后启动ser2net Ser2net –c /et ...

  9. eclipse下maven项目保持原有目录结构配置resin运行环境

    maven项目用起来很方便,但是它的目录结构和eclipse的目录结构是有区别的,故而在eclipse下的maven项目,直接运行调试是有一些问题的. 为了方便maven项目的运行调试,因而也就有了像 ...

  10. hadoop io PART1

    数据正确性检测的技术,通常使用checksum,在数据进行传输前,计算一个checksum值,传输到目标地之后,再根据新的文件计算checksum值,如果不匹配,则说明数据损坏或被改变.只能校验,不提 ...