我最近才研究过 Promise(JS 不是我的强项),我不确定执行此操作的正确方法是什么。 promise 应该防止右漂移代码,但是当我最终得到一些复杂的逻辑时,无论如何我最终都会嵌套得太深,所以我确信我做错了。
如果我将成功和失败都作为 json 值返回,并且我也想处理格式错误的 json,我会立即考虑执行以下操作:
fetch('json').then(function (result) {
return result.json();
}).catch(function (result) {
console.error("Json parse failed!");
console.error(result.text);
}).then(function (wat) {
// if (!result.ok) { throw...
}).catch(function (wat) {
// Catch http error codes and log the json.errormessage
});
当然,这是行不通的。这是典型的同步代码。但这是我首先想到的。我看到的问题:
- 如何获取响应和 json 输出?
- 如何获得错误和成功的单独控制流?
- 如何捕获两种类型响应的 json 解析错误?
我最好的尝试是嵌套到我可能会使用回调的位置,但它最终不起作用,因为我仍然没有解决上述任何问题:
fetch('json').then(function (response) {
if (!response.ok) {
throw response;
}
}).then(
function (response) {
response.json().then(function (data) {
console.log(data);
});
},
function (response) {
response.json().then(function (data) {
console.error(data.errormessage);
});
}
).catch(function () {
console.error("Json parse failed!");
// Where's my response????
});
“正确”的方法是什么? (或者至少减少错误)
最佳答案
如果您无论如何都想调用 response.json()
(对于成功和失败的响应)并且希望将响应数据一起使用 response
。使用Promise.all:
fetch('json')
.then(response => Promise.all([response, response.json()]))
.then(([response, data]) => {
if (!response.ok) {
console.error(data.errormessage);
} else {
console.log(data);
}
})
.catch(err => {
if (/* if http error */) {
console.error('Http error');
} else if (/* if json parse error */)
console.error('Json parse failed');
} else {
console.error('Unknown error: ' + err);
}
});
关于javascript - 使用 Promise 的正确心态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46378403/