【问题标题】:Manipulation with multiples fetch and then使用多个 fetch 然后进行操作
【发布时间】:2022-02-01 18:22:41
【问题描述】:

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

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中每个角色的数据

我认为我的代码是一团糟,但我开始学习承诺,如果代码很糟糕,对不起

【问题讨论】:

  • await.then() 是替代语法。在任何给定的功能中,不要混合使用它们。

标签: javascript api promise fetch


【解决方案1】:
.then((body) => {
  const [index] = body.results;
  const ceo = index.episode 
  let friends = [];
  friends.push(ceo);
  return fetchAll(friends);
    
})

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

【讨论】:

  • 你好,我改变了,这个改变看起来更干净了,但是我遇到了同样的问题,后来 fetchAll(friends2) 得到了这个结果:[ { error: 'There is nothing here.' } ] 并且不知道为什么,当我登录 friends2 时,我有 url 数组,理论上 fetchall 需要工作。
  • 您好,我尝试访问您使用的 API,值 episode 已经是数组。因此,您的 friendsfriends2 的值将是 [ ["link1", "link2"] ] 那样,不要将剧集推入另一个数组。只需将episode 直接传递给fetchAll() 函数即可。
猜你喜欢
  • 2022-08-20
  • 1970-01-01
  • 2014-12-20
  • 1970-01-01
  • 1970-01-01
  • 2021-10-31
  • 2015-09-20
  • 1970-01-01
  • 2014-02-10
相关资源
最近更新 更多