2018-09-16 admin


什么是promise,Bare bones Promises/A+ implementation



This is a simple implementation of Promises. It is a super set of ES6 Promises designed to have readable, performant code and to provide just the extensions that are absolutely necessary for using promises today.

For detailed tutorials on its use, see

N.B. This promise exposes internals via underscore (_) prefixed properties. If you use these, your code will break with each new release.

travis dep npm downloads



$ npm install promise


You can use browserify on the client, or use the pre-compiled script that acts as a polyfill.

<script src=""></script>

Note that the es5-shim must be loaded before this library to support browsers pre IE9.

<script src=""></script>


The example below shows how you can load the promise library (in a way that works on both client and server using node or browserify). It then demonstrates creating a promise from scratch. You simply call new Promise(fn). There is a complete specification for what is returned by this method in Promises/A+.

var Promise = require('promise');

var promise = new Promise(function (resolve, reject) {
  get('', function (err, res) {
    if (err) reject(err);
    else resolve(res);

If you need domains support, you should instead use:

var Promise = require('promise/domains');

If you are in an environment that implements setImmediate and don’t want the optimisations provided by asap, you can use:

var Promise = require('promise/setimmediate');

If you only want part of the features, e.g. just a pure ES6 polyfill:

var Promise = require('promise/lib/es6-extensions');
// or require('promise/domains/es6-extensions');
// or require('promise/setimmediate/es6-extensions');

Unhandled Rejections

By default, promises silence any unhandled rejections.

You can enable logging of unhandled ReferenceErrors and TypeErrors via:


Due to the performance cost, you should only do this during development.

You can enable logging of all unhandled rejections if you need to debug an exception you think is being swallowed by promises:

  {allRejections: true}

Due to the high probability of false positives, I only recommend using this when debugging specific issues that you think may be being swallowed. For the preferred debugging method, see Promise#done(onFulfilled, onRejected).

rejection-tracking.enable(options) takes the following options:

  • allRejections (boolean) - track all exceptions, not just reference errors and type errors. Note that this has a high probability of resulting in false positives if your code loads data optimisticly
  • whitelist (Array<ErrorConstructor>) - this defaults to [ReferenceError, TypeError] but you can override it with your own list of error constructors to track.
  • onUnhandled(id, error) and onHandled(id, error) - you can use these to provide your own customised display for errors. Note that if possible you should indicate that the error was a false positive if onHandled is called. onHandled is only called if onUnhandled has already been called.

To reduce the chance of false-positives there is a delay of up to 2 seconds before errors are logged. This means that if you attach an error handler within 2 seconds, it won’t be logged as a false positive. ReferenceErrors and TypeErrors are only subject to a 100ms delay due to the higher likelihood that the error is due to programmer error.


Before all examples, you will need:

var Promise = require('promise');

new Promise(resolver)

This creates and returns a new promise. resolver must be a function. The resolver function is passed two arguments:

  1. resolve should be called with a single argument. If it is called with a non-promise value then the promise is fulfilled with that value. If it is called with a promise (A) then the returned promise takes on the state of that new promise (A).
  2. reject should be called with a single argument. The returned promise will be rejected with that argument.

Static Functions

These methods are invoked by calling Promise.methodName.


(deprecated aliases: Promise.from(value), Promise.cast(value))

Converts values and foreign promises into Promises/A+ promises. If you pass it a value then it returns a Promise for that value. If you pass it something that is close to a promise (such as a jQuery attempt at a promise) it returns a Promise that takes on the state of value (rejected or fulfilled).


Returns a rejected promise with the given value.


Returns a promise for an array. If it is called with a single argument that Array.isArray then this returns a promise for a copy of that array with any promises replaced by their fulfilled values. e.g.

Promise.all([Promise.resolve('a'), 'b', Promise.resolve('c')])
  .then(function (res) {
    assert(res[0] === 'a')
    assert(res[1] === 'b')
    assert(res[2] === 'c')


Non Standard

Takes a function which accepts a node style callback and returns a new function that returns a promise instead.


var fs = require('fs')

var read = Promise.denodeify(fs.readFile)
var write = Promise.denodeify(fs.writeFile)

var p = read('foo.json', 'utf8')
  .then(function (str) {
    return write('foo.json', JSON.stringify(JSON.parse(str), null, '  '), 'utf8')


Non Standard

The twin to denodeify is useful when you want to export an API that can be used by people who haven’t learnt about the brilliance of promises yet.

module.exports = Promise.nodeify(awesomeAPI)
function awesomeAPI(a, b) {
  return download(a, b)

If the last argument passed to module.exports is a function, then it will be treated like a node.js callback and not parsed on to the child function, otherwise the API will just return a promise.

Prototype Methods

These methods are invoked on a promise instance by calling myPromise.methodName

Promise#then(onFulfilled, onRejected)

This method follows the Promises/A+ spec. It explains things very clearly so I recommend you read it.

Either onFulfilled or onRejected will be called and they will not be called more than once. They will be passed a single argument and will always be called asynchronously (in the next turn of the event loop).

If the promise is fulfilled then onFulfilled is called. If the promise is rejected then onRejected is called.

The call to .then also returns a promise. If the handler that is called returns a promise, the promise returned by .then takes on the state of that returned promise. If the handler that is called returns a value that is not a promise, the promise returned by .then will be fulfilled with that value. If the handler that is called throws an exception then the promise returned by .then is rejected with that exception.


Sugar for Promise#then(null, onRejected), to mirror catch in synchronous code.

Promise#done(onFulfilled, onRejected)

Non Standard

The same semantics as .then except that it does not return a promise and any exceptions are re-thrown so that they can be logged (crashing the application in non-browser environments)


Non Standard

If callback is null or undefined it just returns this. If callback is a function it is called with rejection reason as the first argument and result as the second argument (as per the node.js convention).

This lets you write API functions that look like:

function awesomeAPI(foo, bar, callback) {
  return internalAPI(foo, bar)
    .then(null, retryErrors)

People who use typical node.js style callbacks will be able to just pass a callback and get the expected behavior. The enlightened people can not pass a callback and will get awesome promises.




转载请注明:文章转载自 JavaScript中文网 []



Promise 是异步编程的一种解决方案,比传统的解决方案——回调函数和事件——更合理和更强大。它由社区最早提出和实现,ES6 将其写进了语言标准,统一了用法,原生提供了Promise对象。 所谓Promise,简单说就是一个容器,里面保存...
写在前面: Promise这一章的顺序对于未接触过使用过Promise的童鞋而言略抽象了,前边几章主要为了说明Promise和之前的异步方式相比有什么优势和它能解决什么问题,后边才详解Promise的API设计和各种场景下如何使用Promi...
基本用法 promise有三种状态:pending(进行中)、fulfilled(已成功)和rejected(已失败),Promise构造函数接受一个函数作为参数,该函数的两个参数分别是resolve和reject,其中resolve函数会...
结合 Promise.all 和 Promise.race 功能的函数
今天,公司内大神问我 Promise 有没有类似 Promise.all 多个并发执行的并且保证数据的顺序,但是又可以完成一个异步操作就执行异步的方法,比如: 这里有 5 个 http 分别耗时 [1000, 2000, 3000, 500...
NPM酷库:pify 将异步函数Promise化
NPM酷库,每天两分钟,了解一个流行NPM库。 所有Node.js标准库和很多第三方库提供的接口都是callback样式的,在ES7标准时代,使用async/await配合Promise才是最佳实践。 昨天我们了解到可以用bluebird库...
es6-promise是什么 什么是es6-promise,A lightweight library that provides tools for organizing asynchronous code es6-promise官网:...
直接上代码: var EventEmitter = require(&#x27;events&#x27;) function myPromise(fn) { this.event = new EventEmitter() thi...
原文地址: 故事要从一道今日头条的笔试题说起~ 题目来源:半年工作经验今日头条和美团面试题面经分享!!!!!...
Promise在vue中的使用 Promise.all()
1、定义promise &lt;script type=&quot;text&#x2F;javascript&quot;&gt; &#x2F;&#x2F; 定义一些公共的属性和方法 const httpUrl = &#x27;http:&#...
支持Promise的Generator Runner
为了更斜体文字好的理解生成器+Promise协同运作模式,自己自定义一个独立工具run(…),它会自动异步运行传递给它的生成器,直到结束 ---------- Examples: &#x2F;&#x2F; 把基于回调的代码转换为基于...