有 2 个 Spotify api 调用,如何将它们放入 1 个 Promise.all?

Have 2 Spotify api calls, how can I put them into 1 Promise.all?

我想在我的多页面 React 应用程序中只调用一次这 2 个 spotify api。我想将这些道具传递给阶段组件。如果可能的话,我希望能够在 1 个获取调用中获取响应数据,例如使用 Promise.all()。但我无法弄清楚如何使用这些 api 调用来执行此操作。任何帮助将不胜感激。

import React, { Component } from 'react';
import Home from './components/SelectPage/Home';
import Phases from './components/PhasePage/Phases';
import About from './components/AboutPage/About';
import Auth from './components/Login/Auth';

import { 
    BrowserRouter as Router, 
    Route, 
} from 'react-router-dom'; 

var Spotify = require('spotify-web-api-js');
var spotifyApi = new Spotify();

class App extends Component {
  constructor(props){
    super(props);
    const params = this.getHashParams(); //tokens saved here
    if (params.access_token && params.refresh_token) {
      window.localStorage.setItem('spotifyToken', params.access_token);
      window.localStorage.setItem('refreshToken', params.refresh_token); 
    }    
    this.state = {
      loggedIn: window.localStorage.getItem('spotifyToken') ? true : false,
      artistsLoaded: false,
      tracksLoaded: false,
      top_artists_ids: [],
      top_tracks_ids: [],
      artist_items : [],
      track_items : []
    };   
  }
  
    componentDidMount(){
      if (window.localStorage.getItem('spotifyToken')){
          spotifyApi.
          setAccessToken(window.localStorage.getItem('spotifyToken'));
          this.spotifyGetTopTrackIds();
          this.spotifyGetTopArtistIds();
       }
    }

    spotifyGetTopTrackIds = () => {
        spotifyApi.getMyTopTracks({ time_range: "long_term",limit: 50})
        .then((data) => {
            var track_ids = data.items.map(function (obj) {
                return obj.id;
            });
            this.setState({
              track_items: data.items,
              top_tracks_ids: track_ids,
              tracksLoaded: true
            })
        },
        function (err) {
            Error();
            console.error(err);
        });
      }
  
      spotifyGetTopArtistIds = () => {
          spotifyApi.getMyTopArtists({ time_range: "long_term", limit: 50})
          .then((data) => {
              var artist_ids = data.items.map(function (obj) {
                  return obj.id;
              });
    
              this.setState({
                artist_items: data.items,
                top_artists_ids: artist_ids,
                artistsLoaded: true
              })
            }, 
            function (err) {
                Error();
                console.error(err);
            });
      }

  render() {
    if (!this.state.artistsLoaded || !this.state.tracksLoaded){
      return <div> Loading...</div>
    }
    return (
        <Router>
          {this.state.loggedIn
            ?
              <div className='App'>
                <Route exact path = '/home' component= {Home}/>
                <Route exact path= '/phases' 
                  render={(props) => 
                  <Phases 
                    top_tracks_ids={this.state.top_tracks_ids} 
                    top_artists_ids={this.state.top_artists_ids}
                    artist_items={this.state.artist_items}
                    track_items={this.state.track_items}
                    {...props}/>}
                  />
                <Route exact path= '/about' component = {About}/>
                <Route exact path= '/' component = {Auth}/>
              </div>
            :<Route path= '/' component = {Auth}/>
        }
        </Router>
    ); 
  }
}
export default App;

我希望这个例子能帮助你理解如何使用Promise.all

function getSpotifyData() {
  const topTracksPromise = spotifyApi.getMyTopTracks({ time_range: 'long_term', limit: 50 })
  const topArtistsPromise = spotifyApi.getMyTopArtists({ time_range: 'long_term', limit: 50 })

  Promise.all([topTracksPromise, topArtistsPromise]).then(([topTracks, topArtists]) => {
    const track_ids = topTracks.items.map((obj) => obj.id)
    const artist_ids = topArtists.items.map((obj) => obj.id)

    // set state etc.
  })
}

不过,我更喜欢async/await :

async function getSpotifyData() {
  const topTracks = await spotifyApi.getMyTopTracks({ time_range: 'long_term', limit: 50 })
  const topArtists = await spotifyApi.getMyTopArtists({ time_range: 'long_term', limit: 50 })

  const trackIds = topTracks.items.map((obj) => obj.id)
  const artistIds = topArtists.items.map((obj) => obj.id)

  // set state etc.
}

不要忘记将其放入 try/catch - 或分别添加 .catch()