Promise的前世今生

简介: 作者:@洗影 Promise 的历史 Promise 是一个古老的概念(最初提出于 1976 年),通常与 future 结合在一起。Future 指的是未来的值,通常在 Promise 里被作为参数和返回值传来传去(但是在有的语境下 Future 又被用来指代类似 Promise 的东西。

原作者:@洗影

Promise 的历史

Promise 是一个古老的概念(最初提出于 1976 年),通常与 future 结合在一起。Future 指的是未来的值,通常在 Promise 里被作为参数和返回值传来传去(但是在有的语境下 Future 又被用来指代类似 Promise 的东西。下文中,我们所说的 future 表示第一种概念)。

Promise 只是一个概念,很多常见语言的标准库都有 Promise 关联的特性(比如 C++ 11 的 std::promisestd::future、Java 8 的 java.util.concurrent.Future、Python 3.2+ 的 concurrent.futures等)。即使标准库里没有,大部分语言里也有第三方实现的 Promise(比如 Ruby 的 Promise gem)。这里主要讨论 JavaScript,特别是 ECMAScript 2015 中的 Promise。

在 JavaScript 的世界里,最早得到广泛使用的 Promise 是 jQuery 的 AJAX 模块中出现的 jQuery.Deferred()。Promise/A+ 标准规定了一系列 API,并配有大量的测试用例,ECMAScript 2015 直接整合了这个标准。

Promise/A+ 提供的 API 非常有限,很多 Promise 库(Q、bluebird 等)在兼容 Promise/A+ 的基础上添加了一些其他的扩展。jQuery 3.0 也已经将 Deferred 迁移成了与 Promise/A+ 兼容。

Promise 的三种状态

依照 Promise/A+ 的定义,Promise 有三种状态:

  • pending: 初始状态,表示既不是 fullfilled,也不是 rejected
  • fulfilled: 表示操作完成
  • rejected: 表示操作失败

另外, fulfilledrejected 一起合称 settled

Promise 的构造函数

构造一个 Promise,最基本的用法如下:

var promise = new Promise(function(resolve, reject) {
    if (...) {  // succeed
        resolve(result);
    } else {   // fails
        reject(Error(errMessage));
    }
});

实例:将 XMLHttpRequest Promise 化

var ajax = (function() {
  'use strict';
  var DONE = 4,
      OK = 200;

  function serialize(obj) {
     var str = [];
     for(var p in obj) {
         if (obj.hasOwnProperty(p)) {
             str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
         }
     }
     return str.join("&");
  }

  function core(method, url, data, headers) {
    if (method === 'GET' && data) {
      url += '?' + serialize(data);
    }

    // Establishing a promise in return
    return new Promise(function(resolve, reject) {
      // Instantiates the XMLHttpRequest
      var xhr = new XMLHttpRequest();
      xhr.open(method, url, true);

      if (headers) {
        for (var key in headers) {
          if (headers.hasOwnProperty(key)) {
            xhr.setRequestHeader(key, headers[key])
          }
        }
      }

      xhr.onreadystatechange = function(e) {
        if (xhr.readyState === DONE) {
          if (xhr.status === OK) {  // pass to then arg1
            resolve(xhr.responseText);
          } else {  // pass to catch/then arg2
            reject(Error(xhr.statusText));
          }
        }
      };

      xhr.onerror = function(e) {
        reject(Error("XMLHttpRequest failed"));
      }

      if (method === 'GET' || !data) {
        xhr.send();
      } else {
        xhr.send(data);
      }
    });
  }

  return {
    'get': function(url, data, headers) {
      return core('GET', url, data, headers);
    },
    'post': function(url, data, headers) {
      return core('POST', url, data, headers);
    },
    'put': function(url, data, headers) {
      return core('PUT', url, data, headers);
    },
    'delete': function(url, headers) {
      return core('DELETE', url, headers);
    }
  };
}());

Instance method

Promise 实例拥有 then 方法(具有 then 方法的对象,通常被称为 thenable)。它的使用方法如下:

promise.then(onFulfilled, onRejected)

接收两个函数作为参数,一个在 fulfilled 的时候被调用,一个在 rejected 的时候被调用,接收参数就是 future,onFulfilled 对应 resolve, onRejected 对应 reject

var promise = new Promise(function(resolve, reject) {
    if (someCondition) {  // succeed
        resolve(1);
    } else {   // fails
        reject("err");
    }
});

promise.then(function(future) {
    console.log(future);  // log 1 if someCondition = true
    return 2;
}, function(err) {
    console.log(err);  // log err if someCondition = false
}).then(function(future) {
    console.log(future);  // log 2 if someCondition = true
});

如果 Promise 被 reject,后面的 then 又没有指定 onRejected,会往后面的 then 的 onRejected 传递 future。

var promise = new Promise(function(resolve, reject) {
    reject("err");
});

promise.then(function(future) {
    console.log(future);   // won't get in here
    return 2;
}).then(function(future) {
    console.log(future);   // won't get in here
}, function(err) {
    console.log(err + " catched in 2nd then"); // log: err catched in 2nd then
});

如果 Promise 被 onRejected 处理,那么 onRejected 的返回值(future)会传给下一个 then 的 onFulfilled

var promise = new Promise(function(resolve, reject) {
    reject("err");
});

promise.then(function(future) {
    console.log(future);
    return 2;
}, function(err) {
    console.log(err);  // log: err
    return "return value in first onRejected"
}).then(function(future) {
    console.log(future); // log: return value in first onRejected
});

如果返回了一个 Promise,在后面的 then 的参数里会被拆开,所以得到的还是 future。这个特性与函数式编程中的 Monad) 有异曲同工之妙:

var promise = new Promise(function(resolve, reject) {
    resolve(1);
});

promise.then(function(future) {
    console.log(future);  // log: 1
    return new Promise(function(resolve, reject) {
        resolve("future in the first then");
    });
}).then(function(future) {
    console.log(future);  // log: future in the first then
});

promise.catch(onRejected)

promise.catch(onRejected) 等于 promise.then(undefined, onRejected)。 未实现 ES5 的环境下(e.g. IE8) catch 作为对象的属性时依然属于保留字,会报错,可以用 promise["catch"] 绕过。

使用之前的例子

var p = ajax
  .get('http://foo.com/api/normal/123', {id: 1234})
  .then(function(response) {
    console.log(response);
    var data = JSON.parse(response);
    return ajax.post('http://foo.com/api/normal',
        JSON.stringify({id: data.content}),
        { "Content-Type": "application/json" });
  }).then(function(response) {
    console.log(response);
  }).catch(function(err) {
    console.log(err);
  });

Static method

Promise.all(iterable)

参数中所有的 Promise resolve 后,then 里包含这些 Promise 的 future。

Promise.all([promise1, promise2, promise3]).then(function(futures) {
    console.log(futures); // [future1, future2, future]
}); 

Promise.race(iterable)

参数中任一 Promise resolve 后,then 里包含最快 resolve 的那个 Promise 的结果。

Promise.race([promise1, promise2, promise3]).then(function(future) {
    console.log(future); // future1 if promise1 is resolved first, etc.
}); 

Promise.resolve(...)

快速创建一个 Promise,如果参数原来是 Promise,返回值跟原来的 Promise 一致,如果原来不是 Promise,参数值会被包装给 then 的第一个参数函数,所以可以用来封装不确定是不是 Promise 的值。

Promise.resolve(1);

// is equivalent to
new Promise(function(resolve, reject) {
    resolve(1);
})
Promise.resolve(1).then(function(future) {
    console.log(future);  // 1
});
Promise.resolve(promise).then(function(future) {
    console.log(future);
});

// is equivalent to
promise.then(function(future) {
    console.log(future);
});

Promise.reject(...)

快速创建一个被 reject 的 Promise,如果参数原来是 Promise,返回值跟原来的 Promise 一致,如果原来不是 Promise,参数值会被包装给 then 的第二个参数函数或者 catch,所以可以用来封装不确定是不是 Promise 的值。

Promise.reject("err");

// is equivalent to
new Promise(function(resolve, reject) {
    reject("err");
})
Promise.reject(1).catch(function(future) {
    console.log(future);  // 1
});
Promise.resolve(promise).catch(function(future) {
    console.log(future);
});

// is equivalent to
promise.catch(function(future) {
    console.log(future);
});

用例

使用 Promise,完成运行时才能确定执行顺序的串行逻辑

假设我们有一些串行的操作,每一步分别写在一个函数里,并且这些函数的返回值都是 Promise,参数接口也统一,在知道它们的执行顺序(如 A-B-C-D)时,我们可以这样写:

A(1).then(B).then(C).then(D);

然而如果它们具体的执行顺序(比如是 A-B-C-D 还是 B-C-A-D)需要在运行时确定,那就无法将这个顺序写在代码里。这个时候我们可以在运行时将函数按顺序放入一个数组 operations,利用 Promise 进行串行执行:

var promise = undefined
for (var i = 0; i < operations.length; ++i) {
  if (typeof promise == 'undefined')
    promise = operations[i];
  else
    promise = promise.then(operations[i]);
}

完成需要多种数据源就绪后才能执行的操作

假设渲染一个页面,需要获取多个表的数据,全部就绪后交给模板引擎。如果数据库操作均有提供 Promise 的接口(如 mongoose):

var userPromise = userdb.query(...);  // promise
var postPromise = postdb.query(...);  // promise
var replyPromise = replydb.query(...);

Promise.all([userPromise, postPromise, replyPromise])
.then(function(result) {
  template.render({
    user: result[0],
    post: result[1],
    reply: result[2]
  });
});

注:如果觉得这里接收参数时硬写下标比较丑,可以借助 ES2015 引入的 destructuring 语法糖

Promise.all([userPromise, postPromise, replyPromise])
.then(function([user, post, reply]) {
  template.render({
    user: user,
    post: post,
    reply: reply
  });
});

完成有依赖的的串行查询

利用在 then 接收的函数里返回 Promise,下一个 then 接收的函数里能得到这个 Promise 拆开后的内容的特性,串行查询的编写就能干净许多。如果原来是回调风格的 API,大约会是这样:

userdb.query(userid, function(err, user) {
  if (err !== null) {
    // error handling
  }
  postdb.query(user.latestPost.id, function(err, post) {
    if (err !== null) {
      // error handling
    }
    replydb.query(post.latestReply.id, function(err, reply) {
      if (err !== null) {
        // error handling
      }
      // use reply to do something...
    });
  });
})

如果依赖一多,回调套回调,就会产生 pyramid of doom) 的效果。如果数据源能提供 Promise 风格的 API,写起来大约是这样:

userdb.query(userid)
.then(function(user) {
  return postdb.query(user.latestPost.id);
}).then(function(post) {
  return replydb.query(post.latestReply.id);
}).then(function(reply) {
  // use reply to do something...
}).catch(function(reason) {
   // error handling
});

虽然还是有一些多余的代码,但是依赖较多时,代码形状不会横向发展,可维护性有所提升,而且可以集中处理错误。

需要注意的是,Promise 仅仅是一层建立在语言之上的抽象,即使代码运行的 JavaScript 环境不提供,也可以使用 polyfill 或者添加了额外扩展的库来提供支持。在编写异步逻辑的时候,使用 Promise 能够在对运行环境侵入性较小的前提下,一定程度上改善代码的可维护性,但依然会出现一些繁琐的 boilerplate code。在能够掌控运行环境(例如 Node.js)的情况下,在 Promise 这个基础设施之上,我们还有更多的语法特性来提高代码的可维护性。

Promises 与 generators

使用 ES 2015 中的 generator,加上一个 spawn helper,用 promise 编写异步逻辑能够更加顺畅。(这里的 spawn 类似于库 co 所提供的功能,虽然 co 更加强大)

这里我们配合 ES 2015 的 arrow function 看看示例(因为支持 generator 的环境,多半也支持 arrow function)。假设有如下两种操作(异步+同步):

function asyncOperation() {
  return new Promise(resolve => {
    setTimeout(function() {
      resolve(Math.random());
    }, Math.random() * 3000);
  });
}

function syncOperation(value) {
  console.log(value);
}

编写一个 spawn helper 如下(使用了 arrow function,改写自 ES2016 spec 中的参考实现)

// Taken from the spec, modified with ES6
function spawn(genF, self) {
  return new Promise((resolve, reject) => { 
    let gen = genF.call(self);  // get the iterator out of the generator

    // nextF could return a generator
    // that throws or returns values/Promises
    function tick(nextF) {

      let next;

      try {
        next = nextF();  // yield is executed here
      } catch(e) {
        reject(e);  // fails
        return;
      }

      if (next.done) {  // finished and succeed
        // spawn finished, next.value be will passed
        // to the then() of the spawn return value
        resolve(next.value);
        return;
      } else { // succeed but not finished i.e. more yield
        // wrap it and pass to next tick
        Promise.resolve(next.value)
        .then( v => {
            tick(() => gen.next(v));  // pass outside
        }, e => {
            tick(() => gen.throw(e));  // throw outside
        });  // pass the async result to tick
      }
    }

    tick(() => gen.next(undefined));  // kickoff
  });
}

使用方法如下,少了许多冗余代码,清晰不少(另外,如果有错误,在这段逻辑里编写 try-catch 后,Promise 中 reject 的结果就可以被捕获):

spawn(function* doWork() {
  console.log("start");

  // what passed to next() will be yielded here
  let a = yield asyncOperation();
  syncOperation("first async result: " + a);
  let b = yield asyncOperation();
  syncOperation("second async result: " + b);
  let c = yield asyncOperation();
  syncOperation("third async result: " + c);

  console.log("done");
  return a + b + c;  // this will be resolved
}, this)
.then(result => console.log("Final result: " + result));

Promises and async/await

结合 ES 2016 的 async function,就不需要自己准备一个 spawn helper 了。

async function fn(/* args */) {
    /* body */
}

相当于

function fn(/* args */) {
    return spawn(function*() {
        /* body */
    }, this);
}

在 generator 中用 yield 与 Promise 交互,在 async function 中则用 await

async function doWork() {
  console.log("start");
  let a = await asyncOperation();
  syncOperation("first async result: " + a);
  let b = await asyncOperation();
  syncOperation("second async result: " + b);
  let c = await asyncOperation();
  syncOperation("third async result: " + c);
  console.log("done");
  return a + b + c;
}


let result = await doWork();
console.log("Final result: " + result);

纯 Promise、generator、async/await 的对比

这个例子来自 async/await 的 spec

只使用 Promise 抽象:

function chainAnimationsPromise(elem, animations) {
    let ret = null;
    let p = currentPromise;
    for(const anim of animations) {
        p = p.then(function(val) {
            ret = val;
            return anim(elem);
        })
    }
    return p.catch(function(e) {
        /* ignore and keep going */
    }).then(function() {
        return ret;
    });
}

使用 generator 后,更少 boilerplate code,错误处理可以使用 try-catch 也更加清晰,但是需要一个 spawn helper:

function chainAnimationsGenerator(elem, animations) {
    return spawn(function*() {
        let ret = null;
        try {
            for(const anim of animations) {
                ret = yield anim(elem);
            }
        } catch(e) { /* ignore and keep going */ }
        return ret;
    });
}

使用 async/await,几乎没有 boilerplate code,直接写逻辑即可,而且不需要自己写 spawn

async function chainAnimationsAsync(elem, animations) {
    let ret = null;
    try {
        for(const anim of animations) {
            ret = await anim(elem);
        }
    } catch(e) { /* ignore and keep going */ }
    return ret;
}

Promise 的相关应用

Promise 更多地像一个基础设施,在这种抽象之上已经建立起了不少库与 API:

参考/深入阅读

目录
相关文章
|
16天前
|
前端开发 API 容器
说说你对 promise 的了解
说说你对 promise 的了解
9 0
|
5月前
|
前端开发 小程序 JavaScript
promise 应用
promise 应用
35 0
|
6月前
|
前端开发 JavaScript 测试技术
6 # 实现简单的 promise
6 # 实现简单的 promise
21 0
|
3月前
|
前端开发 JavaScript
Promise 详解
Promise 详解
28 0
|
4月前
|
前端开发
Promise
Promise
34 1
|
8月前
|
存储 JSON 前端开发
深入使用 Promise
前面各种铺垫已经好了,现在我们一起来用一用Promise!
48 0
|
8月前
|
前端开发
什么是promise,解决了什么
什么是promise,解决了什么
105 0
|
9月前
|
前端开发 JavaScript
深入理解Promise
深入理解Promise
65 0
|
前端开发 JavaScript
探索Promise的应用
探索Promise的应用
|
JavaScript 前端开发
Day23 Promise
Promise 是 JS 中进行异步编程的一种解决方案。
72 0