首页 > 解决方案 > 当我的数据位于 .then 承诺中时,如何在下一个 js 中的 API 路由中发送我的响应

问题描述

我正在使用带有 axios 的下一个 js,并且我在 .then 中有一个 .then 承诺。我想用我抓取的数据来响应 api 请求,但是如果我将 res 放在 .then 中,则无法访问,但我不知道如何从 .t​​hen 中获取数据。通常使用异步等待我返回值并为函数创建一个变量,但这似乎不适用于.then。

这是我的代码

let data;

  axios
    .post(
      "https://accounts.spotify.com/api/token",
      serialize({
        grant_type: "client_credentials",
      }),
      {
        headers: {
          Authorization: "Basic " + auth,
        },
      }
    )
    .then((res) => {
      axios
        .get(
          `https://api.spotify.com/v1/search?q=${name}&type=episode&market=US`,
          {
            headers: {
              Authorization: `Bearer ${res.data.access_token}`,
              "Content-Type": "application/json",
            },
          }
        )
        .then(function (response) {
          // handle success
          console.log(response.data.episodes);
          data = response.data.episodes;
        })
        .catch(function (error) {
          // handle error
          console.log(error);
        })
        .then(function () {
          // always executed
        });
    })
    .catch((err) => {
      console.log(err);
    });

  res.status(200).json({ data: data });

任何帮助将不胜感激谢谢

标签: javascriptnode.jsaxiosnext.jses6-promise

解决方案


以下修复了它

const data = axios
    .post(
      "https://accounts.spotify.com/api/token",
      serialize({
        grant_type: "client_credentials",
      }),
      {
        headers: {
          Authorization: "Basic " + auth,
        },
      }
    )
    .then((res) => {
      const test = axios
        .get(
          `https://api.spotify.com/v1/search?q=${name}&type=episode&market=US`,
          {
            headers: {
              Authorization: `Bearer ${res.data.access_token}`,
              "Content-Type": "application/json",
            },
          }
        )
        .then(function (response) {
          // handle success
          // console.log(response.data.episodes);
          return response.data.episodes;
        })
        .catch(function (error) {
          // handle error
          console.log(error);
        });

      return test;
    })
    .catch((err) => {
      console.log(err);
    });

  const boy = async () => {
    console.log("data", await data);
    res.status(200).json({ data: await data });
  };
  boy();

推荐阅读