如何使用Axios和Typescript等待响应?

时间:2019-07-31 20:14:59

标签: javascript node.js typescript asynchronous axios

我需要您的帮助来调整我的方法以等待axios响应。基本上,我向WebService发送请求,并且需要等待响应以捕获返回值并调用另一个方法。

我尝试在通话中使用async / await,但我可能用错了。

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; });
}

此代码首先记录“ console.log(search);”的结果输出如下:

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

此后显示axios响应。

1 个答案:

答案 0 :(得分:0)

您的“ 创建”函数未返回承诺,它是一个无效的返回类型函数。 另外,您需要在“ Axios ”之类的异步任务之前添加等待。 Object.values不是异步任务。

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}`,
            }
        })
    }
}