【发布时间】: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