LEARNING JAVASCRIPT - Trang 231

countdown

(

5

).

then

(

function

() {

console

.

log

(

"countdown completed successfully"

);

},

function

(

err

) {

console

.

log

(

"countdown experienced an error: "

+

err

.

message

);

}
);

In this example, we didn’t bother assigning the returned promise to a variable; we just

called its

then

handler directly. That handler takes two callbacks: the first one is the

fulfilled callback, and the second is the error callback. At most, only one of these

functions will get called. Promises also support a

catch

handler so you can split up

the two handlers (we’ll also store the promise in a variable to demonstrate that):

const

p

=

countdown

(

5

);

p

.

then

(

function

() {

console

.

log

(

"countdown completed successfully"

);

});

p

.

catch

(

function

(

err

) {

console

.

log

(

"countdown experienced an error: "

+

err

.

message

);

});

Let’s modify our

countdown

function to have an error condition. Imagine we’re super‐

stitious, and we’ll have an error if we have to count the number 13.

function

countdown

(

seconds

) {

return

new

Promise

(

function

(

resolve

,

reject

) {

for

(

let

i

=

seconds

;

i

>=

0

;

i

--

) {

setTimeout

(

function

() {

if

(

i

===

13

)

return

reject

(

new

Error

(

"DEFINITELY NOT COUNTING THAT"

));

if

(

i

>

0

)

console

.

log

(

i

+

'...'

);

else

resolve

(

console

.

log

(

"GO!"

));

}, (

seconds

-

i

)

*

1000

);

}
});
}

Go ahead and play around with this. You’ll notice some interesting behavior. Obvi‐

ously, you can count down from any number less than 13, and it will behave nor‐

mally. Count down from 13 or higher, and it will fail when it gets to 13. However…

the console logs still happen. Calling

reject

(or

resolve

) doesn’t stop your function;

it just manages the state of the promise.
Clearly our

countdown

function needs some improvements. Normally, you wouldn’t

want a function to keep working after it had settled (successfully or otherwise), and

ours does. We’ve also already mentioned that the console logs aren’t very flexible.

They don’t really give us the control we’d like.
Promises give us an extremely well-defined and safe mechanism for asynchronous

tasks that either fulfill or reject, but they do not (currently) provide any way to report

Promises | 207

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.