2016-05-12 77 views
0

我想有一個future價值,它可以解決的價值,掛起或拒絕以類似的方式scala的未來。未來的價值與es6承諾

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'); 

是否有內置的東西或我會不得不重新發明自行車?

+0

發現這一點: https://github.com/seangenabe/es6-deferred/blob/master/deferred .js – Alex

+0

因此,您在發佈後8分鐘回答了您自己的問題? – trincot

回答

1

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'); 
+0

如果將解析函數保存在某處,Promise具有該功能。 – Paarth