如何在Promise.prototype.then()中包含条件

时间:2019-06-08 16:49:04

标签: javascript node.js

我正在使用axios来获取API,并且需要根据返回的数据包括一个条件:

axios.get('https://api.url.endpoint).then(response => ())

我将如何根据响应做出条件语句(特别是检查响应的属性是否返回null)?

感谢您的帮助。

在以下响应中使用if..else语句不起作用。

axios.get('https://api.url.endpoint).then(response => (
if (response.data != null) { }
))

1 个答案:

答案 0 :(得分:2)

如果结果不是 null,如果该概念仍然会引发错误,则

axios.get('...')
  .then(res => {
    if (!res.data) throw new Error('No data');

    return res.data
  });

尽管如此,我认为使用async / await

会更容易
const res = await axios.get('...');
if (res.data) {
  // happy day scenario
} else {
  // bad day scenario
}