我只是最近才看过承诺(JS不是我的强项),我不知道做这个的正确方法是什么。承诺应该防止代码的正确漂移,但是当我以某种复杂的逻辑结束时,我最终还是会嵌套得太深,所以我确信我做错了。
如果我将成功和失败都作为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
});当然,这是行不通的。这是典型的同步代码。但这是我首先想到的。我能看到的问题:
我最好的尝试是嵌套到可以使用回调的程度,但它最终还是不起作用,因为我还没有解决上述任何一个问题:
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????
});做这件事的“正确”方法是什么?(或者至少少错一点)
发布于 2017-09-23 10:43:23
如果您想无论如何调用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);
}
});发布于 2017-09-23 10:28:30
您不应该对承诺中的控制流使用异常,就像不使用承诺时一样。这就是为什么fetch本身不只是拒绝200以外的状态代码的承诺。
这里有一个建议,但答案必然取决于你的具体需要。
fetch('json').then(function (response) {
if (!response.ok) {
response.json().then(function (data) {
console.error(data.errorMessage);
});
return ...;
}
return response.json().catch(function () {
console.error("Json parse failed!");
return ...;
});
}).catch(function (e) {
console.error(e);
return ...;
});https://stackoverflow.com/questions/46378403
复制相似问题