Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/443.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如果在fetch中布尔值为false,如何跳过next.then()?_Javascript_Json_If Statement_Promise_Fetch - Fatal编程技术网

Javascript 如果在fetch中布尔值为false,如何跳过next.then()?

Javascript 如果在fetch中布尔值为false,如何跳过next.then()?,javascript,json,if-statement,promise,fetch,Javascript,Json,If Statement,Promise,Fetch,我在first中添加了if语句。然后()根据foo的数据给出不同的路径。length是否为0 问题是代码总是访问第二个。然后()无论布尔值是true还是false 结果是: 拒绝访问索引。js:31 未定义的“另一条路径”索引。js:34 我找到了一个和我相似的人,但他使用了promise,而不是fetch,我不知道如何在fetch子句中使用reject 有解决此问题的提示吗?您可以使用throw触发Promise中的错误。代码示例: // foo.json [] // bar.json [

我在first
中添加了
if
语句。然后()
根据foo的
数据给出不同的路径。length
是否为0

问题是代码总是访问第二个
。然后()
无论布尔值是
true
还是
false

结果是:

拒绝访问索引。js:31

未定义的“另一条路径”索引。js:34

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


有解决此问题的提示吗?

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

// 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')
    })
}
对于您的代码:

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

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

我完全忘记了
throw
关键字。非常感谢你。这很有帮助。
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);
    }
}