[英]How can I fetch two api in javascript?
I need to fetch two APIs, one has all username and country and another API has user info. 我需要获取两个API,一个具有所有用户名和国家/地区,另一个API具有用户信息。 So I fetch the first API:
因此,我获取了第一个API:
enter code here
let getUsername= new Promise(function(resolve,reject){
fetch(userUrl).then(function(response){
return response.json()
}).then(function(response){
return response.map((x=>x.name))
}).then(function(response){
var name=response
console.log(name)
return name
})
})
and it the return value should be like that 它的返回值应该像这样
[{name:'carlos',country:'mexico'},{name:'jenny',country:'germany'}]
and that array is only exist in getUsername fuction but I need to use that to fetch another api 并且该数组仅存在于getUsername功能中,但我需要使用它来获取另一个api
names=[] enter code here 名称= []在此处输入代码
let promisesArray = names.map(name=> {
// make a new promise for each element of cities
return new Promise((resolve, reject) => {
let url = `http:// userinfo/${name}`
request(url, function(error, response, body) {
if (error) {
reject(error);
}
var data = JSON.parse(body)
var results = data.main
// resolve once we have some data
resolve(results);
});
})
})
Promise.all(promisesArray)
.then(function(results) {
console.log(results)
})
.catch(function(error) {
console.log(error)
})
so what I need is I need to make a user array that only has a name from first API, so I can use map function to fetch second API. 因此,我需要做一个仅具有第一个API名称的用户数组,以便可以使用map函数获取第二个API。
Just destructure name
out in your map
call when you define users
: 定义
users
时,只需在map
调用中分解name
:
const users = userarray.map(({ name }) => fetch(`http://api.userdata.${name}`));
If you want it to be called username
too, just alias it: 如果您也希望将其称为
username
,只需为其加上别名:
const users = userarray.map(({ name: username }) => fetch(`http://api.userdata.${username}`));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.