Javascript 如果在fetch中布尔值为false,如何跳过next.then()?
我在firstJavascript 如果在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 [
中添加了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);
}
}