微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript-我可以对Bluebird.js做出“懒惰”承诺吗?

我想要一个等到then被调用后才能运行的承诺.就是说,如果我从没真正打过电话,诺言将永远无法实现.

这可能吗?

解决方法:

创建一个函数,该函数在第一次调用时创建并返回一个promise,但在每次后续调用时都返回相同的promise:

function getResults() {
  if (getResults.results) return getResults.results;

  getResults.results = $.ajax(...); # or where ever your promise is being built

  return getResults.results;
}

承诺不能以支持延迟加载的方式工作.由异步代码创建承诺以传达结果.在异步代码被调用之前,根本没有承诺.

您当然可以编写一个类似于惰性的对象,并进行延迟调用,但是生成这些承诺的代码将大不相同:

// Accepts the promise-returning function as an argument
LazyPromise = function (fn) {
  this.promise = null;
  this.fn = fn
}

LazyPromise.prototype.then = function () {
  this.promise = this.promise || fn();
  this.promise.then.apply(this.promise, arguments)
}

// Instead of this...
var promise = fn();

// You'd use this:
var promise = new LazyPromise(fn);

最好使用这种不常用的方法来使承诺的实际创建变得懒惰(如上述示例所示),而不是尝试使承诺自己负责延迟评估.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐