[英]How to “finally” on promise with then/catch?
How to do a proper finally on a promise? 最终如何正确地履行诺言?
Can I add a finally equivalent to this? 我可以添加一个最终等同于此的东西吗?
functionReturningPromise()
.then(success => {})
.catch(error => {})
or should I do it this way (does this even work as expected)? 还是我应该这样做(这是否按预期工作)?
functionReturningPromise()
.then(success => {},error => {}).then(() => { /* finally code */ })
You can use 您可以使用
.finally()
Example: 例:
functionReturningPromise()
.then(data=>console.log(data))
.catch(error=>console.log(error))
.finally(()=>console.log("FINISH"))
The finally is called allways 最后被称为反正
You can do this in two ways: 您可以通过两种方式执行此操作:
yourPromiseFunction
.then(function(json) { /* process your JSON further */ })
.catch(function(error) { console.log(error); /* this line can also throw, e.g. when console = {} */ })
.finally(function() { console.log("finally") });
Example: 例:
yourPromiseFunction.then(() => console.log('Resolved'))
.catch(() => console.log('Failed'))
.then(() => console.log('This is your finally'));
Yes, finally works with promises. 是的,终于可以兑现承诺了。
Example: 例:
let isLoading = true;
fetch(myRequest).then(function(response) {
var contentType = response.headers.get("content-type");
if (contentType && contentType.includes("application/json")) {
return response.json();
}
throw new TypeError("Oops, we haven't got JSON!");
})
.then(function(json) {
/* process your JSON further */
})
.catch(function(error) {
console.log(error); /* this line can also throw, e.g. when console = {} */
})
.finally(function() {
isLoading = false;
});
For further reference refer https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally 有关更多参考,请参阅https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.