首页 > 解决方案 > 为 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);
      })
} 

标签: javascriptjsonapi

解决方案


复制对象和引用变量时出现问题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);
  });
}

推荐阅读