为了账号安全,请及时绑定邮箱和手机立即绑定

.then()在嵌套promise.all和fetch完成之前执行

.then()在嵌套promise.all和fetch完成之前执行

蝴蝶刀刀 2021-05-13 14:15:18
我正在尝试创建一个使用Javascript中的抓取功能从API检索数据的应用程序。这是几个网址的JSON结构myapi.com/list返回:[{{id:111,user:nam1},{id:222,user:nam2}]然后,我必须使用以下其中一个id示例进行另一个请求:myapi.com/list/111返回:[{id:111,user:name1,description: "some text",public:true}]示例:myapi.com/list/111/posts返回:[{a1:"some data",a2:"some data2"},{b1:"some data",b2:"some data2"},{c1:"some data",c2:"some data2"}]由于几个原因,我需要创建一个函数,该函数以以下格式返回将所有这些分组的1个数组:   [    {id:111,user:name1,description: "some text",public:true,     posts:[{a1:"some data",a2:"some data2"},{b1:"some data",b2:"some data2"},{c1:"some data",c2:"some data2"}]    },    {id:222,user:name2,description: "some text2",public:true    posts:[{a1:"some data",a2:"some data2"},{b1:"some data",b2:"some data2"},{c1:"some data",c2:"some data2"}    }    ]这是我的主程序,由于setTimeOut,它可以正常工作:    Promise.all([FetchFunctionThatworks(),FetchfunctionWithPrblm() ])    .then(values => new State(values[0], values[1]))    .then(state => {console.log(state) ;       setTimeout(function(){      functionA(state); // a function that prints some html with the result of the FetchfunctionWithPrblm  },200)   ;} )    .catch(reason => console.error(reason));我希望删除setTimeout,但是问题是我的.then()中的代码在承诺被解决之前调用了functionA,因此我得到的结构缺少“帖子”,而setTimeOut我得到了所需的输出。这是我的FetchfunctionWithPrblm()function FetchfunctionWithPrblm() {  const url = serverUrl+ "list/";   return fetch(url).then(    id_list => id_list.json()  ).then(    list_data => Promise.all(      list_data.map(topic => fetch(url +topic.id)      .then(response =>  response.json()  )      )    ) /**end 1st promise.all */  ) .then(ListNopost =>{    ListNopost.map( single_entry =>{      Promise.all( [fetch( url + single_entry.id+ '/posts').then(resp=>resp.json() ) ] )      .then (posts_data =>{        single_entry.posts=posts_data[0];      })    })    return ListNopost;  })}不是promise.all应该只在promise解决后才返回吗?有人可以告诉我我在做什么错吗?并帮助我修复它吗?
查看完整描述

添加回答

代码语言

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号