Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为fetchapi处理不同的变量_Javascript_Json_Api - Fatal编程技术网

Javascript 为fetchapi处理不同的变量

Javascript 为fetchapi处理不同的变量,javascript,json,api,Javascript,Json,Api,如何用一个函数从不同的fetch中填充不同的变量 填充后,我想将缓存导出到另一个js文件,但我不知道如何操作: var Acache = {}, Bcache = {} ; fetch(APIcall1).then( res => { handlecache(res, Acache); } ); fetch(APIcall2).then( res => { handlecache(res, Bcache); } );

如何用一个函数从不同的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);
  });
}

填充后,我想将缓存导出到另一个js文件
-因此,在稍后的某个未知时间(异步就是这样工作的),您想同步导出结果吗?是的,同步!在用Cronjob执行我的脚本之后,我想在我的网站@Jaromanda Xwell上模板化数据客户端,这对年轻玩家来说是个陷阱。。。如果以异步方式获得结果,则无法可靠地以同步方式处理它们,因为时间只朝一个方向流动,即向前