ES6 承诺的未来价值

future value with es6 promises

我想要一个 future 值,它可以用值解决,以类似于 scala 的 future 的方式挂起或拒绝。

var username = new Promise();
username.then(x => console.log(x));

// half an hour later, triggered by user click or by ajax, or by timer, or  
username.resolve('john');

有内置的东西吗?还是我必须重新发明自行车?

Deferred.js 在 https://github.com/seangenabe/es6-deferred/blob/master/deferred.js

提供
"use strict";

var Promise = global.Promise || require('es6-promise').Promise;

var Deferred = function() {
  this.promise = new Promise((function(resolve, reject) {
    this.resolve = resolve;
    this.reject = reject;
  }).bind(this));

  this.then = this.promise.then.bind(this.promise);
  this.catch = this.promise.catch.bind(this.promise);
};

module.exports = Deferred;

用法示例:

var d = new Deferred();
d.then(x => console.log(x));
d.resolve('boo');