【发布时间】:2021-06-06 19:40:48
【问题描述】:
我有一个问题,或者至少我没有解决方案。
我通过地图获得了一些 API 调用,我可以控制台记录所有结果,这很棒,但问题是我想将所有结果合并到一个数组中。
var alpha = ['a', 'b', 'c', 'd', 'e'];
alpha.map(alpha => {
fetch(`https://myurl.com/api/members/page?prefix=${alpha}`)
.then(res => res.json())
.then(data => matches.push)
.then(() => console.log(matches))
})
我想我必须做一些等待什么的?
我的 API 响应如下所示:
{"list_complete":true,"keys":
[
{
"username": "name.com",
"uuid": "-47c9-88b6-2474090c7927",
"user_type": 1,
"subscribed": "false",
"lastLogin": 1611066809086,
"profile": {
"name": "Name Lastname",
"email": "name.com",
"uuid": "3e92f458-6331-2-88b6-2474090c7927",
"address": "",
"history": [
{
"titleId": "5fac58f764e6710017411e79",
"posterUrl": "url.jpg",
"displayName": "Guns N ´ Roses - Appetite for Democracy",
"t": 0,
"d": 8492.2
},
{
"titleId": "5f7eadb3963c170017a919f3",
"posterUrl": "url.jpg",
"displayName": "Frank Zappa - Apostrophe Overnite Sensation (Classic Albums)",
"t": 7.728575,
"d": 2974.9
},
{
"titleId": "5e4463a395c832405e7effc0",
"posterUrl": "url.jpg",
"displayName": "Bob Marley - Uprising Live!",
"t": 3285.406821,
"d": 6807.7
},
{
"titleId": "5f80c6d0045fdf0017735019",
"posterUrl": "url.jpg",
"displayName": "Van Morrison - In Concert",
"t": 3610.529879,
"d": 4558.29
},
{
"titleId": "5fa85aba9c4a1900177e5cf9",
"posterUrl": "url.jpg",
"displayName": "Iron Maiden - En Vivo!",
"t": 2522.988949,
"d": 3380.5
},
{
"titleId": "5f719cb75d994e0017b429c5",
"posterUrl": "url.jpg",
"displayName": "Placebo - Placebo Live At The O2 Brixton Academy",
"t": 1426.589863,
"d": 5061.89
},
{
"titleId": "5fb3fd1731be640017c2f878",
"posterUrl": "https://slam-assets.s3.eu-north-1.amazonaws.com/staging/5fb3fd1731be640017c2f878/cover/1606214166013_nirvanastaende.jpg",
"displayName": "Nirvana - Nevermind (Classic Albums)",
"t": 0,
"d": 2948.69
}
],
"favourites": [
"5f9039ed1279d600170378c2",
"5facf94364e6710017411e7d",
"5e4463a395c832405e7effc0"
]
},
"subscription": null
}
]
}
而我要收集的数据在每个用户名下的一个叫history的数组中。
【问题讨论】:
-
查看
Promise.all及相关方法。您打算如何使用结果值? -
酷。谢谢。会看看。收集完所有数据后,我会将所有用户历史记录合二为一。
-
如果
matches是一个数组,matches.push不会做太多事情。如果您想将data推入matches(或then(data => { matches.push(data); }),则需要.then(matches.push),这样您就不会得到matches(push的输出)的新长度的响应。 -
查看此处查看使用
Promise.all()的示例:flaviocopes.com/how-to-wait-multiple-promises-javascript -
@HereticMonkey 我知道,你不能再编辑评论了,但为了记录,
.then(matches.push)将无法工作,因为method context being lost;它必须是.then(matches.push.bind(matches))。
标签: javascript node.js svelte sapper