基于 Promise 的函数记忆化 [英] Memoization of promise-based function

查看:15
本文介绍了基于 Promise 的函数记忆化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何记住基于 Promise 的函数?

How can I memoize a promise-based function?

直接记住函数就足够了吗?

Would straightforward memoization of the function suffice?

function foo() {
    return new Promise((resolve, reject) => {
      doSomethingAsync({ success: resolve, fail: reject });
    });
};

这就够了吗?

var fooMemoized = memoize(foo);

注意:此问题已更新以删除延迟反模式.

Note: this question has been updated to remove the deferred anti-pattern.

推荐答案

是的,这就足够了.Promise 是简单的返回值,这是它们的巨大好处 - 与回调相反,在回调中记忆代码会很糟糕.

Yes, that will suffice. Promises are simple return values, which is their great benefit - in contrast to callbacks, where memoisation code would be horrible.

如果您的承诺库确实支持某种取消,您可能只想确保记忆的承诺是不可取消的.另请注意,这种形式的备忘录也会记住拒绝,因此您无法通过重试"来从错误中恢复.

You only might want to make sure that the memoized promise is uncancellable, if your promise library does support some kind of cancellation. Also notice that this form of memoisation remembers rejections as well, so you can't recover from errors by "trying again".

这篇关于基于 Promise 的函数记忆化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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