0
votes

I need your help to adjust my methods to wait for a axios response. Basically, I send a request to an WebService and I need wait the response to catch the return and call another method.

I've tried to use async/await on my calls but I probably used it wrong.

class PlaylistController {
  // Metodo inicial para criacao da playlist
  public async create(req: Request, res: Response): Promise<Response> {
    let artists = req.body.bands;
    artists = artists.split(',');

    const search = await Object.values(artists)
      .map((artistsName): Promise<AxiosResponse> => this.searchArtists(artistsName));
    console.log(search);

  }

  private searchArtists = async (artistName): Promise<AxiosResponse> => axios.get(`${API_URL}/search`, {
    params: {
      q: artistName,
      type: 'artist',
    },
    headers: {
      Authorization: `${TOKEN_TYPE} ${REFRESH_TOKEN}`,
    },
  }).then((response): AxiosResponse => { console.log(response.data.artists); return response; })
    .catch((error) => { console.log(error.response.data); return error; });
}

This code first log the result of the "console.log(search);" with this output:

[Promise { pending },
 Promise { pending },
 Promise { pending } ]

After that is showed the axios response.

1
Your first await is simply awaiting the result of the map function, which is synchronous and returns immediately. If you want to wait for all of the promises to return, use Promise.all. - Heretic Monkey

1 Answers

2
votes

Your "create" function is not returning a promise, its a void return type function. Also, you need to add await before async task like "Axios". Object.values is not an async task.

class PlaylistController {
    // Metodo inicial para criacao da playlist
    public create(req: Request, res: Response): void {
      let artists = req.body.bands;
      artists = artists.split(',');

      search = Object.values(artists).map((artistsName): any => this.searchArtists(artistsName));
      console.log(search)
    }

    private searchArtists = async (artistName): Promise<AxiosResponse> => {
        return await axios.get(`${API_URL}/search`, {
            params: {
              q: artistName,
              type: 'artist',
            },
            headers: {
              Authorization: `${TOKEN_TYPE} ${REFRESH_TOKEN}`,
            }
        })
    }
}