簡體   English   中英

es6承諾帶來的未來價值

[英]future value with es6 promises

我想擁有一個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');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM