我只是最近才研究了承诺(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
});
当然,这行不通。这是刻板印象的同步代码。但这是想到的第一件事。我可以看到的问题:
- 我如何获得响应和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);
}
});
您不应该使用异常来对控制流程中的诺言,而不是不使用承诺时应应有的更多。这就是为什么获取本身不仅拒绝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 ...;
});