首页 > 解决方案 > 如何在一个函数中同时使用来自两个不同端点的 json 数据?

问题描述

所以我想从两个不同的端点提取数据,并将它们同时发送到一个函数,作为所述函数的参数。

function otherFunc(jsonData1, jsondata2){
//do stuff
}



function getJsonData(url1,url2){
fetch(url1);
fetch(url2);
.then((response) => response.json())
.then((data) => otherFunc(data));
}
getJsonData(someUrl1, someOtherUrl2);

所以我知道如何将一组数据发送到一个函数,并且我知道如何发出多个 get 请求,但我不知道如何将两组 jsonData 发送到与 params 相同的函数。

提前致谢

标签: javascriptjsonapi

解决方案


使用 async/await 更清晰一些

function otherFunc(jsonData1, jsonData2) {
  //do stuff
}

async function getJsonData(url1, url2) {
  const res1 = await fetch(url1);
  const res2 = await fetch(url2);

  const json1 = await res1.json();
  const json2 = await res2.json();

  otherFunc(json1, json2);
}

getJsonData(someUrl1, someOtherUrl2);

或者使用Promise.all()

function otherFunc(jsonData1, jsonData2) {
  //do stuff
}

async function getJsonData(url1, url2) {
  const resArr = await Promise.all(
    [url1, url2].map(url => fetch(url))
  );

  const [json1, json2] = await Promise.all(
    resArr.map(res => res.json())
  );

  otherFunc(json1, json2)
}

getJsonData(someUrl1, someOtherUrl2);

或者...

function otherFunc(jsonData1, jsonData2) {
  //do stuff
}

function getJsonData(url1, url2) {
  Promise.all([
    fetch(url1),
    fetch(url2)
  ]).then(responses => //map the returned promises to resolve json
    Promise.all(responses.map(res => res.json()))
  ).then(([json1, json2]) => // destructure resolved json
    otherFunc(json1, json2)
  ).catch(error =>
    // if there's an error, log it
    console.log(error));
}

getJsonData(someUrl1, someOtherUrl2);

推荐阅读