最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I wait for a response using Axios and Typescript? - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question asked Jul 31, 2019 at 20:14 DouglasNicksonDouglasNickson 1551 gold badge4 silver badges15 bronze badges 2
  • 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 Commented Jul 31, 2019 at 20:17
  • 1 Possible duplicate of How do I await a list of Promises in JavaScript/TypeScript? – Heretic Monkey Commented Jul 31, 2019 at 20:18
Add a ment  | 

1 Answer 1

Reset to default 2

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}`,
            }
        })
    }
}
发布评论

评论列表(0)

  1. 暂无评论