我可以做一个“懒惰”吗?与Bluebird.js保证? [英] Can I do a "lazy" promise with Bluebird.js?

查看:63
本文介绍了我可以做一个“懒惰”吗?与Bluebird.js保证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个等到 然后 在运行之前被调用。也就是说,如果我从未实际调用然后,则承诺永远不会运行。

I want a promise that waits until then is called before it runs. That is, if I never actually call then, the promise will never run.

这可能吗?

推荐答案

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

Make a function which creates and returns a promise on first invocation, but returns the same promise on each subsequent invocation:

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

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

  return getResults.results;
}

Promise不能以支持延迟加载的方式工作。 Promise由异步代码创建,以便传达结果。在调用异步代码之前,只需就没有承诺

Promises don't work in such a way that they could support lazy loading. Promises are created by asynchronous code in order to communicate a result. Until the async code has been invoked, there simply is no promise.

你当然可以编写一个类似于承诺的对象来执行惰性调用,但是生成这些承诺的代码会有很大不同:

You could certainly write a promise-like object which did lazy invocation, but code that generated these promises would be very different:

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

这种不常见的用法更好地制作承诺的实际创建懒惰(如上面的例子),而不是试图让承诺自己负责懒惰评估。

It's better in this uncommon use to make the actual creation of the promise lazy (as in either above example), rather than trying to make promises themselves responsible for lazy-evaluation.

这篇关于我可以做一个“懒惰”吗?与Bluebird.js保证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆