多次获取操作然后

问题描述 投票:0回答:1

我正在学习对学校的承诺,还有很多我不明白的事情。

async function getCompanion(name){
const response = await fetch("https://rickandmortyapi.com/api/character/?name=" + name)
if(response.status !== 200) throw `HTTP error: ${response.status}`;
const data =  response.json()
return data
.then((body) => {
  const [index] = body.results;
  const ceo = index.episode 
  let friends = [];
  friends.push(ceo);
  return fetchAll(friends);
   
    
})
.then((body2) => {
  const [index2] = body2;
  const ceo2 = index2.characters
  let friends2 = [];
  friends2.push(ceo2);
  //console.log(friends2)
  return fetchAll(friends2)
}).then((body3) =>{
  console.log(body3);
  
})

.catch( (error) => {
  console.log(`Error: ${error}`)
})
}



async function fetchAll(urls){
  const res = await Promise.all(urls.map(u => fetch(u)))
  const jsons = await Promise.all(res.map(r => r.json()))
  console.log(jsons)
  return jsons
  
}

我想做的事:

它是一个异步函数,当您传递名称时,您会得到与所使用的名称共享剧集的同伴的名称,我的问题是第一个 .then 按我想要的方式工作,我得到了角色参与的剧集,但是第二个

fetchAll
不起作用,我不知道为什么,想法是第二个
fetchAll
获取
friends2
中每个字符的数据。

我认为我的代码很混乱,但我开始学习 Promise,如果代码很糟糕,我很抱歉。

javascript promise fetch-api
1个回答
0
投票
.then((body) => {
  const [index] = body.results;
  const ceo = index.episode 
  let friends = [];
  friends.push(ceo);
  return fetchAll(friends);
    
})

进行此更改,它应该会起作用。 fetchAll()是一个返回promise的异步函数,你需要在它之前放置await或者直接返回它,因为无论如何你都没有使用那个characters常量。

© www.soinside.com 2019 - 2024. All rights reserved.