【问题标题】:How to skip next .then() if boolean is false in fetch? [duplicate]如果布尔值在获取中为假,如何跳过下一个 .then()? [复制]
【发布时间】:2020-05-20 07:56:57
【问题描述】:
// foo.json
[]
// bar.json
[
  {
    "name": "bar",
    "type": "whatever" 
  }
]
function getJSON(path) {
  return fetch(`http://localhost:4000/admin/${path}`)
    .then(response => response.json())
}
function getStart() {
  getJSON('foo')
    .then(data => {
      if (data.length == 0) {
        return getJSON('bar')
        // Look at bar.json and access to next .then() method
      }
      console.log('Access Denied')
      // skip the next .then() method and exit.
    })
    .then(data => {
      console.log(data, 'another then path')
    })
}

我在第一个 .then() 中添加了 if 语句,用于提供不同的路径取决于 foo 的 data.length 是否为 0。

问题是代码总是访问第二个.then(),无论布尔值是true 还是false

这是结果:

拒绝访问 index.js:31

未定义的“另一个路径” index.js:34

我找到了一个和我类似的question,但他使用的是promise,而不是fetch,而且我不知道如何在fetch 子句中使用reject

有什么技巧可以解决这个问题吗?

【问题讨论】:

标签: javascript json if-statement promise fetch


【解决方案1】:

您可以使用throw 来触发 Promise 中的错误。代码示例:

const promise1 = new Promise(function(resolve, reject) {
  throw 'Uh-oh!';
});

promise1.catch(function(error) {
  console.error(error);
});
// expected output: Uh-oh!

对于您的代码:

function getStart() {
  getJSON('foo')
    .then(data => {
      if (data.length === 0) {
        return getJSON('bar')
        // Look at bar.json and access to next .then() method
      } else {
         console.log('Access Denied');
         throw new Error('Access Denied');
      }
    })
    .then(data => {
      console.log(data, 'another then path')
    })
    .catch(e => {
      console.log('Error', e);
    }
}

【讨论】:

  • 我完全忘记了 throw 关键字。太感谢了。很有帮助。
猜你喜欢
  • 2013-02-21
  • 2015-04-01
  • 2020-12-29
  • 2018-10-07
  • 2020-01-05
  • 1970-01-01
  • 1970-01-01
  • 2013-10-13
  • 2017-12-11
相关资源
最近更新 更多