LEARNING JAVASCRIPT - Trang 235

const

c

=

new

Countdown

(

5

)

.

on

(

'tick'

,

i

=>

console

.

log

(

i

+

'...'

));

c

.

go

()

.

then

(

launch

)

.

then

(

function

(

msg

) {

console

.

log

(

msg

);

})
.

catch

(

function

(

err

) {

console

.

error

(

"Houston, we have a problem...."

);

})

One of the advantages of promise chains is that you don’t have to catch errors at every

step; if there’s an error anywhere in the chain, the chain will stop and fall through to

the

catch

handler. Go ahead and change the countdown to a 15-second superstitious

countdown; you’ll find that

launch

is never called.

Preventing Unsettled Promises

Promises can simplify your asynchronous code and protect you against the problem

of callbacks being called more than once, but they don’t protect you from the prob‐

lem of promises that never settle (that is, you forget to call either

resolve

or

reject

).

This kind of mistake can be hard to track down because there’s no error…in a com‐

plex system, an unsettled promise may simply get lost.
One way to prevent that is to specify a timeout for promises; if the promise hasn’t set‐

tled in some reasonable amount of time, automatically reject it. Obviously, it’s up to

you to know what “reasonable amount of time” is. If you have a complex algorithm

that you expect to take 10 minutes to execute, don’t set a 1-second timeout.
Let’s insert an artificial failure into our

launch

function. Let’s say our rocket is very

experimental indeed, and fails approximately half the time:

function

launch

() {

return

new

Promise

(

function

(

resolve

,

reject

) {

if

(

Math

.

random

()

<

0.5

)

return

;

// rocket failure

console

.

log

(

"Lift off!"

);

setTimeout

(

function

() {

resolve

(

"In orbit!"

);

},

2

*

1000

);

// a very fast rocket indeed

});
}

In this example, the way we’re failing is not very responsible: we’re not calling

reject

,

and we’re not even logging anything to the console. We just silently fail half the time.

If you run this a few times, you’ll see that sometimes it works, and sometimes it

doesn’t…with no error message. Clearly undesirable.
We can write a function that attaches a timeout to a promise:

Promises | 211

Liên Kết Chia Sẽ

** Đây là liên kết chia sẻ bới cộng đồng người dùng, chúng tôi không chịu trách nhiệm gì về nội dung của các thông tin này. Nếu có liên kết nào không phù hợp xin hãy báo cho admin.