我正在尝试通过对 Spotify 的循环 API 请求来创建一个承诺。Spotify 的工作方式使我一次只能获得 100 首曲目,因此我检查是否还有更多曲目并重新运行该功能,直到所有曲目都附加到“项目”列表中。现在,承诺在 1 个请求后解决,但我需要在所有请求完成后解决。我的代码:
function getItems(myUrl) {
return new Promise((resolve, reject) => {
let items = []
request.post(authOptions, function(error, response, body) {
if (!error && response.statusCode === 200) {
// use the access token to access the Spotify Web API
var token = body.access_token;
var options = {
url: myUrl,
headers: {
'Authorization': 'Bearer ' + token
},
json: true
};
request.get(options, function(error, response, body) {
if (error) return reject(error);
for (var item of body['items']) {
items.push(item)
}
if (response.body.next != null) {
getItems(response.body.next)
}
resolve(items)
})
} else {
reject(error)
}
})
return items
})
}
getItems('https://api.spotify.com/v1/playlists/1vZFw9hhUFzRugOqYQh7KK/tracks?offset=0')
.then(res => console.log(res))
郎朗坤
POPMUISE
相关分类