简体   繁体   中英

Handle different variables for fetch api

How I can fill different vars from different fetch with one function?

And after filling I want to export the caches to another js file, but I don't know how to do that:

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);
      })
} 

There is a problem with copying the object and referring to the variable in handlecache()

This should work as you'd expect:

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);
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM