node.js 函数调用顺序,Spotify Web API

Posted

技术标签:

【中文标题】node.js 函数调用顺序,Spotify Web API【英文标题】:node.js function call order, Spotify Web API 【发布时间】:2021-03-11 05:47:29 【问题描述】:

我正在尝试将 Spotify Web API 与 node.js 的包装器一起使用。在执行任何 API 调用之前,我需要设置访问令牌。在我的脚本中,我先调用setAccessToken 函数,然后在下面调用一些API 请求。但是,由于 node.js 的异步特性,我的 setAccessToken 方法在我的 API 请求之后被调用,这导致 API 请求失败。在调用下面的 API 请求之前,如何确保我的 setAccessToken 函数返回(API 请求行以 spotifyApi.getMySavedTracks 调用开头)

app.get('/callback', (req, res) => 
  var code = req.query.code || null;
  if (code === null) 
      console.log("code is null");
  

  async function authorize() 
    const data = await spotifyApi.authorizationCodeGrant(code);
    // console.log('The token expires in ' + data.body['expires_in']);
    // console.log('The access token is ' + data.body['access_token']);
    // console.log('The refresh token is ' + data.body['refresh_token']);
    // Set the access token on the API object to use it in later calls
    accesToken = data.body['access_token'];
    refreshToken = data.body['refresh_token'];
    spotifyApi.setAccessToken(accesToken);
    spotifyApi.setRefreshToken(refreshToken);
  

  try 
    authorize();
   catch (err) 
    console.log('Something went wrong!', err);
  

  spotifyApi.getMySavedTracks(
    limit : lim,
    offset: 1
  )
  .then(function(data) 
    return data.body.items;
  , function(err) 
    console.log('Something went wrong!', err);
  )
  .then(function(items) 
    let ids = [];
    items.forEach(function(item) 
      ids.push(item.track.id);
    )
    return spotifyApi.getAudioFeaturesForTracks(ids); //2xc8WSkjAp4xRGV6I1Aktb
  )
  .then(function(data) 
    let songs = data.body.audio_features;
    //console.log(songs);
    let filteredSongURIs = [];
    songs.forEach(function(song) 
      if ((song.energy >= moodScore-offset) && (song.energy <= moodScore+offset)) 
        filteredSongURIs.push(song.uri);
      
    )

    //Create Playlist with filtered songs
    spotifyApi.createPlaylist('Mooder Playlist',  'description': 'My description', 'public': true )
    .then(function(data) 
      return data.body.id;
    , function(err) 
      console.log('Something went wrong!', err);
    )
    .then(function(playlist) 
      spotifyApi.addTracksToPlaylist(playlist, filteredSongURIs)
    )
    .then(function(data) 
      console.log('Added tracks to playlist!');
    , function(err) 
      console.log('Something went wrong!', err);
    );
    
  , function(err) 
    console.log(err);
  );


  res.redirect('/testAPI');
);

【问题讨论】:

【参考方案1】:

您可以将setAccessToken 之后的所有代码包装到另一个then 中,或者您可以将awaitPromise 结束:

// Add `async` here
app.get('/callback', async (req, res) => 
  var code = req.query.code || null;
  if (code === null) 
      console.log("code is null");
  
  try 
    const data = await spotifyApi.authorizationCodeGrant(code);
    // console.log('The token expires in ' + data.body['expires_in']);
    // console.log('The access token is ' + data.body['access_token']);
    // console.log('The refresh token is ' + data.body['refresh_token']);
    // Set the access token on the API object to use it in later calls
    accesToken = data.body['access_token'];
    refreshToken = data.body['refresh_token'];
    spotifyApi.setAccessToken(accesToken);
    spotifyApi.setRefreshToken(refreshToken);
   catch (err) 
    console.log('Something went wrong!', err);
  

  // The rest of your code

【讨论】:

原来spotifyApi.authorizationCodeGrant 不是异步函数。因为我得到了“SyntaxError: await is only valid in async function”@emi 问题不在于spotifyApi.authorizationCodeGrant,而在于调用它的函数需要声明为async才能被允许使用await 我将所有代码放在异步函数中的 try 块中,并在 try 中调用它。但是我遇到了同样的问题 @Khashhogi 抱歉,我无法理解最后的评论。 相应地更新您的问题

以上是关于node.js 函数调用顺序,Spotify Web API的主要内容,如果未能解决你的问题,请参考以下文章

Spotify API Web:没有 Node.js 的 OAuth

Node.js Express Spotify API保存在会话中

Node Js Async 未按正确顺序运行并跳过承诺

如何从 Spotify Search API 获取数据并将其解析为 JSON? [在 node.js 中

验证 spotify web api 不起作用

如何确保 Node.js 中的这些函数链按顺序执行(使用 Promise)?