Javascript 如何解析嵌套承诺数组
我有一个承诺数组,我希望保持嵌套,因为它们是起始和结束位置坐标,所以这两组坐标应该在内部数组中保持在一起 我正在努力解决这些承诺,但似乎无法实现。我正在尝试映射外部数组以在内部数组上执行Promise.all,但它没有给我期望的结果 这是我的密码:Javascript 如何解析嵌套承诺数组,javascript,promise,Javascript,Promise,我有一个承诺数组,我希望保持嵌套,因为它们是起始和结束位置坐标,所以这两组坐标应该在内部数组中保持在一起 我正在努力解决这些承诺,但似乎无法实现。我正在尝试映射外部数组以在内部数组上执行Promise.all,但它没有给我期望的结果 这是我的密码: const promises = idArr.map(route => route.map(id => (this.get(`places/${id}`)))); const places = promises.map(async rou
const promises = idArr.map(route => route.map(id => (this.get(`places/${id}`))));
const places = promises.map(async route => (
await Promise.all(route)
));
其中,承诺
是:
[
[ Promise { <pending> }, Promise { <pending> } ],
[ Promise { <pending> }, Promise { <pending> } ],
[ Promise { <pending> }, Promise { <pending> } ],
[ Promise { <pending> }, Promise { <pending> } ],
[ Promise { <pending> }, Promise { <pending> } ],
[ Promise { <pending> }, Promise { <pending> } ],
[ Promise { <pending> }, Promise { <pending> } ],
[ Promise { <pending> }, Promise { <pending> } ],
[ Promise { <pending> }, Promise { <pending> } ],
[ Promise { <pending> }, Promise { <pending> } ]
]
[
[承诺{},承诺{}],
[承诺{},承诺{}],
[承诺{},承诺{}],
[承诺{},承诺{}],
[承诺{},承诺{}],
[承诺{},承诺{}],
[承诺{},承诺{}],
[承诺{},承诺{}],
[承诺{},承诺{}],
[承诺{},承诺{}]
]
此代码提供以下输出:
[
Promise { <pending> },
Promise { <pending> },
Promise { <pending> },
Promise { <pending> },
Promise { <pending> },
Promise { <pending> },
Promise { <pending> },
Promise { <pending> },
Promise { <pending> },
Promise { <pending> }
]
[
承诺{},
承诺{},
承诺{},
承诺{},
承诺{},
承诺{},
承诺{},
承诺{},
承诺{},
承诺{}
]
我尝试了映射承诺的不同组合。但在我看来,这应该是使其工作的方法,但我显然缺少了一些东西。您缺少了一个嵌套级别的
承诺。所有:
试试这个:
Promise.all(promises.map(x => Promise.all(x)).then(console.log);
如果您已经在数组中有承诺
那你就这么做吧
const promises = idArr.map(route => route.map(id => (this.get(`places/${id}`))));
Promice.all(promises).then(result=> console.log(result))
Promise.all(places)
是一个承诺,当所有内部承诺都被取消时,该承诺将得到解决。