javascript - 如何在一个函数中同时使用来自两个不同端点的 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 相同的函数。
提前致谢
解决方案
使用 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);
推荐阅读
- c++ - 我可以通过这个类的实例访问一个类的成员类型吗?
- vba - 从主题中提取特定的字符串格式进行排序
- php - 每 x 帖子使用模数交替行和列
- functional-programming - 斐波那契与记忆长生不老药
- html - CSS 仅更改现有样式
- python - Nginx 500 POST 到数据库时出错,但它实际上发布
- c - 错误地使用 InterlockedCompareExchange 以原子方式复制值?
- spring - 使用 Jaeger 跟踪检测在 Docker 容器中执行的 Spring-Boot 应用程序
- swift - 自定义范围运算符 - Swift 4.1
- angular - 返回不能在 canActivate 中使用 Observable.toPromise():Angular 4