【问题标题】:API check functionAPI检查功能
【发布时间】:2019-07-27 10:08:29
【问题描述】:

我正在尝试创建一个 IF 语句,用于检查此 API 调用函数的结果,并在返回结果时退出。

function fetchYelp() {
let token = '<token>';
axios.get('https://api.yelp.com/v3/businesses/search?term=Church on the rock&location=saint peters, MO 63376',{
    headers: {
        Authorization: 'Bearer ' + token
    }
})
    .then(res => {
        console.log(res.data);
    })
    .catch(err => {
        console.log(err)
    });

}

fetchYelp();

function fetchWhitePages() {
axios.get('https://proapi.whitepages.com/3.0/business?api_key=<apiKey>&address.city=Saint Peters&address.country_code=US&address.postal_code=63376&name=Church on the rock')
    .then(res => {
        console.log(res.data);
    })
    .catch(err => {
        console.log(err)
    });

}

fetchWhitePages();

我正在画一个空白。

【问题讨论】:

  • 我没有看到 if 语句。
  • 嗨,凯文,这是我难以理解的部分。我想在 if 语句中传入这两个 api 调用,但在找到结果时退出
  • 那么……你想发出两个请求,然后在 if 语句中使用两个请求的结果?
  • @KevinB 我想先传入 Yelp api ca,如果它返回结果,那么我想退出而不是调用 whitePages?如果yelp没有返回结果,我要下一个函数api调用run(whitePages)

标签: node.js api http express axios


【解决方案1】:

目前你没有returning 任何东西,你只是记录函数调用的数据。

这是一个例子:

function fetchYelp() {
  let token = '<token>';

    axios.get('https://api.yelp.com/v3/businesses/search?term=Church on the rock&location=saint peters, MO 63376',{
        headers: {
            Authorization: 'Bearer ' + token
        }
    })
    .then(res => {
      if (!res.data) {
        // you should do something here so that you know there's no data, but returning here would exit out
        return;
      };

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

带有异步/等待的ESNext:

async fetchYelp() {
  let token = '<token>';

  try {
    const res = await axios.get('https://api.yelp.com/v3/businesses/search?term=Church on the rock&location=saint peters, MO 63376',{
        headers: {
            Authorization: 'Bearer ' + token
        }
    })

    if (!res.data) {
      // again return something here, i'm just using an empty object as an example
      return {};
    }

    return res.data
  } catch (err) {
    // throw can also be treated similar to a return statement
    throw new Error(err)
  }

}

【讨论】:

  • 我有一个 fetchYelp 和 fetchWhitePages 函数。您认为我可以在 if 下插入第二个函数并返回数据?
  • @Chris,如果 fetch 非常相似,您可以使其真正通用和模块化,以便 fetchYelp 和 fetchWhitePages 可以具有相同的功能。
  • 当你返回数据时(如return;),我该如何找回呢?
  • @Chris 好吧,如果没有什么可返回的,你就不能。我的if 语句检查是否有任何数据已经存在,如果没有则返回空值以完成函数的调用。
  • 有没有办法检查 API 返回数组是否为空,以继续下一个 api 调用?比如 if(res.data.)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-05
  • 2011-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多