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

.then() is executed before nested promise.all and fetch are done

我正在尝试创建一个应用程序,使用 Javascript 中的提取从 API 检索数据。这是几个 url

的 JSON 结构

myapi.com/list returns: [{id:111, user:nam1},{id:222, user:nam2}] 然后我必须用其中一个 ID 做另一个请求 示例:myapi.com/list/111 returns:

[{id:111,user:name1,description: "some text",public:true}]

示例:myapi.com/list/111/posts returns:

[{a1:"some data",a2:"some data2"},{b1:"some data",b2:"some data2"},{c1:"some data",c2:"some data2"}]

出于几个原因,我需要创建一个函数,returns 1 array grouping all these in following format:

   [
    {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() 中的代码在 promise 解决之前调用了 functionA,所以我得到的结构缺少 "posts",而我得到的是 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 不应该 return 只有当 promise 被解决的时候吗? 有人可以告诉我我做错了什么吗?并帮助我修复它?

提前致谢

您的问题在这里:

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 永远不会 returned,所以你的主要承诺在 fetchs 之前解决。另请注意,map 不是突变器,如果您希望它包含在新数组中,则必须 return 一个值。

试试这个:

var promises = ListNopost.map(single_entry => {
    return fetch(url + single_entry.id + '/posts')
        .then(resp => resp.json())
        .then(posts_data => {
            single_entry.posts = posts_data[0]
            return single_entry
        })
})
return Promise.all(promises)