Javascript 将异步函数中的数据返回到稍后要处理的列表中(删除异步函数)

Javascript 将异步函数中的数据返回到稍后要处理的列表中(删除异步函数),javascript,asynchronous,async-await,request,Javascript,Asynchronous,Async Await,Request,我的代码: function getItems(myUrl) { 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 = bo

我的代码:

function getItems(myUrl) {
  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) {
        for (var item of body['items']) {
          items.push(item)
        }
        if (response.body.next != null) {
          getItems(response.body.next)
        }
      })
    }
  })
  return items
}
console.log(getItems('https://api.spotify.com/v1/playlists/1vZFw9hhUFzRugOqYQh7KK/tracks?offset=0'))
函数将数据添加到函数中定义的“项”列表中。每次我尝试控制台记录函数的返回时,都会得到一个空列表,因为它直接跳过返回项,返回一个空列表。我需要一种方法使函数在返回列表之前等待


谢谢

由于您在实现它时遇到了困难,下面是使用Promise的代码

函数getItems(myUrl){
返回新承诺((解决、拒绝)=>{
让项目=[]
post(authOptions、函数(错误、响应、正文){
如果(!error&&response.statusCode==200){
//使用访问令牌访问Spotify Web API
var token=body.access\u token;
变量选项={
url:myUrl,
标题:{
“授权”:“持票人”+代币
},
json:true
};
获取(选项、函数(错误、响应、正文){
如果(错误)返回拒绝(错误);
对于(主体['items']的变量项){
项目。推送(项目)
}
if(response.body.next!=null){
getItems(response.body.next)
}
解决(项目)
})
}否则{
拒绝(错误)
}
})
退货项目
})
}
//您必须将其放入异步函数中
日志(等待getItems('https://api.spotify.com/v1/playlists/1vZFw9hhUFzRugOqYQh7KK/tracks?offset=0'))
//也可以使用then子句
getItems('https://api.spotify.com/v1/playlists/1vZFw9hhUFzRugOqYQh7KK/tracks?offset=0')
.then(res=>console.log(res))

这是否回答了您的问题?老实说,它可能会,但我很难实现它https://api.spotify.com/v1/playlists/1vZFw9hhUFzRugOqYQh7KK/tracks))^^^^^语法错误:缺少)在参数列表之后