我应该在兑现承诺之前还是之后更新我的缓存?

编程入门 行业动态 更新时间:2024-10-24 08:25:18
本文介绍了我应该在兑现承诺之前还是之后更新我的缓存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在我的应用程序中,我从 API 获取信息并将其缓存.如果缓存未命中,而我最终要检索数据来存储它,那么我应该什么时候更新缓存?

当一个 promise 被执行时,resolve 不会停止函数其余部分的执行.我想尽快返回信息,所以如果我先解决promise,然后更新缓存,我真的会获得任何性能优势吗?或者我是否为比赛条件或类似的事情做好了准备?

这个

new Promise((resolve, reject) => {让结果 = getThingFromApi();解决(结果);更新缓存(结果);//返回承诺})

还是这个?

new Promise((resolve, reject) => {让结果 = getThingFromApi();更新缓存(结果);//返回承诺解决(结果);})

解决方案

当一个 promise 被执行时,resolve 不会停止函数其余部分的执行.我想尽快返回信息,所以如果我先解决promise,然后更新缓存,我真的会获得任何性能优势吗?或者我是否为比赛条件或类似的事情做好了准备?

不,这与性能无关.resolve 调用不执行任何实际工作,例如调用 Promise 回调,它仅设置一个标志,表示现在已使用值解析了 Promise,并安排了稍后的解析工作.resolve() 本质上是异步的.因此,您在这里称呼它的位置根本无关紧要,引入异步正是为了防止这种竞争条件.

您唯一应该担心的是,如果您在之后放置 resolve(result) 将不会执行它,并且 updateCache(result) 确实会抛出异常.>

In my application, I get information from an API and cache it. If the cache misses and I end up retrieving the data to store it, when should I update the cache?

When a promise is executed, resolve does not stop the execution of the rest of the function. I want to return the information as soon as possible, so if I resolve the promise first, and then update the cache, would I actually reap any performance benefits? Or am I setting myself up for race conditions or something like that down the road?

This

new Promise((resolve, reject) => { let result = getThingFromApi(); resolve(result); updateCache(result); // returns promise })

or this?

new Promise((resolve, reject) => { let result = getThingFromApi(); updateCache(result); // returns promise resolve(result); })

解决方案

When a promise is executed, resolve does not stop the execution of the rest of the function. I want to return the information as soon as possible, so if I resolve the promise first, and then update the cache, would I actually reap any performance benefits? Or am I setting myself up for race conditions or something like that down the road?

No, it doesn't matter for performance at all. The resolve call doesn't do any actual work like invoking the promise callbacks, it only sets a flag that the promise is now resolved with a value and schedules the rest of the resolution work for later. resolve() is essentially asynchronous. And therefore it doesn't matter at all where you call it here, the asynchrony was introduced precisely to prevent these kind of race conditions.

The only worry you should have is that resolve(result) will not be executed if you place it afterwards and updateCache(result) does throw an exception.

更多推荐

我应该在兑现承诺之前还是之后更新我的缓存?

本文发布于:2023-10-27 11:37:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1533241.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:缓存

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!