javascript - 为 fetch api 处理不同的变量
问题描述
如何使用一个函数填充来自不同 fetch 的不同变量?
填充后我想将缓存导出到另一个 js 文件,但我不知道该怎么做:
var Acache = {}, Bcache = {} ;
fetch(APIcall1).then(
res => {
handlecache(res, Acache);
}
);
fetch(APIcall2).then(
res => {
handlecache(res, Bcache);
}
);
function handlecache(res, cache) {
res.json()
.then((j) => {
cache(!! not working!!) = j;
console.log(acache, bcache);
})
}
解决方案
复制对象和引用变量时出现问题handlecache()
这应该像您期望的那样工作:
const Cache = {
A: {},
B: {}
};
fetch(APIcall1).then(res => {
handlecache(res, 'A'); // Pass the obj key instead of whole object
});
fetch(APIcall2).then(res => {
handlecache(res, 'B');
});
function handlecache(res, key) {
res.json().then(j => {
// Copy response data and save to the end of Cache using spread syntax
Cache[key] = { ...Cache[target], ...j };
console.log(Cache);
});
}
推荐阅读
- javascript - 如何在 VUE 中通过 v-model 直接更新嵌套对象数组值?
- c# - 我已经创建了两个线程,但没有一个线程正在访问它应该命中的方法
- c - C 加密和解密中的凯撒密码,ASCII 值太高
- r - SVM 预测结果
- swift - 用函数提取数据后如何填写UItableview?
- python - 运行后的命令 cv2.imshow()、waitKey()、destroyAllWindows() 关闭镜像后继续运行
- python - 检查 gdb 内 gdb 中附加的程序的功能是否退出......并将其应用于 if 条件
- python - 测试。使用堆叠参数化装饰器时定义预期结果的最佳方法?
- javascript - 如何链接 MongoDB 集合
- google-calendar-api - Google Calendar API - 在插入 + 事件期间未发送邀请在非 Gmail 帐户中不可见