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

node.js function call order, Spotify Web API

我正在尝试将 Spotify Web API 与 node.js 的包装器一起使用。在执行任何 API 调用之前,我需要设置访问令牌。在我的脚本中,我先调用 setAccessToken 函数,然后在下面调用一些 API 请求。但是,由于 node.js 的异步性质,我的 setAccessToken 方法在我的 API 请求之后被调用,这导致失败的 API 请求。在调用下面的 API 请求之前,如何确保我的 setAccessToken 函数 returns(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');
});

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

// 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