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.
awaitis simply awaiting the result of themapfunction, which is synchronous and returns immediately. If you want to wait for all of the promises to return, usePromise.all. - Heretic Monkey