我应该在兑现承诺之前还是之后更新我的缓存? [英] Should I update my cache before or after I resolve my promise?

查看:58
本文介绍了我应该在兑现承诺之前还是之后更新我的缓存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我从 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.

这篇关于我应该在兑现承诺之前还是之后更新我的缓存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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