本文共 2942 字,大约阅读时间需要 9 分钟。
are one of the best things that happened to JavaScript in the past few years.
是JavaScript在过去几年中发生的最好的事情之一。
When we invoke a function that returns a promise, we chain the then()
method of the promise to run a function when the promise resolves.
当我们调用一个返回诺言的函数时,我们会链接诺言的then()
方法以在诺言解决时运行一个函数。
Here’s an example using the :
这是使用的示例:
fetch('/data.json') .then(response => { console.log(response.status) })
What if there is an error during the fetch()
call? Perhaps the network is unavailable. Or the network request returns an error.
如果在fetch()
调用期间出现错误怎么办? 也许网络不可用。 或网络请求返回错误。
The promise will reject. A promise will look something like this:
诺言将被拒绝。 一个承诺将如下所示:
const thePromise = new Promise((resolve, reject) => {})
Inside the promise we are passed 2 parameters, 2 functions. Inside the body, if all goes find, the resolve() function is called:
在promise中,我们传递了2个参数和2个函数。 在体内,如果一切顺利,将调用resolve()函数:
const thePromise = new Promise((resolve, reject) => { resolve('ok') //you can pass any value})
If something bad happens, the reject() function is called:
如果发生错误,则将调用reject()函数:
const thePromise = new Promise((resolve, reject) => { reject('error message') //you can pass any value})
If something goes bad, we must handle the promise rejection. We do so using the catch()
method of the promise:
如果事情变坏了,我们必须处理承诺的拒绝。 我们使用promise的catch()
方法来做到这一点:
thePromise .catch(error => { console.error(error) })
We must always add a catch()
, otherwise promises will silently fail.
我们必须始终添加catch()
,否则诺言将无声地失败 。
We can chain catch()
to a then()
method:
我们可以将catch()
到then()
方法:
thePromise .then(response => { console.log(response) }) .catch(error => { console.error(error) })
Or even multiple ones, if you have a chain of promises:
甚至多个,如果您有一系列承诺:
const thePromise = new Promise((resolve, reject) => { resolve({ doSomething: function() { return new Promise((resolve, reject) => { reject('error!') //you can pass any value }) } })})thePromise .then(response => { return response.doSomething() }) .then(response => { console.log(response) }) .catch(error => { console.log(error) })
In this case, if thePromise
is rejected, the execution jumps directly to the catch()
method.
在这种情况下,如果thePromise
被拒绝,执行将直接跳转到catch()
方法。
You can add the catch()
method in the middle of two then()
methods, but you will not be able to break the chain when something bad happens. And the return value of catch()
(which will have the undefined
value if not specified) will be passed to the following then()
.
您可以在两个then()
方法的中间添加catch()
方法,但是当发生不好的情况时,您将无法断开链。 然后catch()
的返回值catch()
如果未指定,将具有undefined
值)将被传递给随后的then()
。
It’s best, in my opinion, to leave catch()
at the end of the chain, and use it to handle all possible errors.
我认为最好是将catch()
留在链的末尾,并使用它来处理所有可能的错误。
Error handling in my opinion is best in , but sometimes we can’t avoid using promises, so that’s how you can do it.
我认为错误处理最好是在 ,但有时我们无法避免使用promises,因此您可以这样做。
翻译自:
转载地址:http://uamgb.baihongyu.com/