LEARNING JAVASCRIPT - Trang 240

passes and then the concatenated result is written to another file, we already have

what we want. On the other hand, what we may want is for the three files to be read,

and in no sooner than 60 seconds, the results to be written to a fourth file—in which

case, we would want to move the timeout into the

Promise.all

.

Don’t Write Your Own Generator Runner

While it’s a good exercise to write our own generator runner, as we have done with

grun

, there are many nuances and improvements we could make on it. It’s better not

to reinvent the wheel. The

co

generator runner

is full-featured and robust. If you are

building websites, you may want to look into

Koa

, which is designed to work with

co

,

allowing you to write web handlers using

yield

, as we have in

theFutureIsNow

.

Exception Handling in Generator Runners

Another important benefit of generator runners is that they enable exception han‐

dling with

try/catch

. Remember that exception handling is problematic with call‐

backs and promises; throwing an exception inside a callback cannot be caught from

outside the callback. Generator runners, because they enable synchronous semantics

while still preserving asynchronous execution, have a side benefit of working with

try/catch

. Let’s add a couple of exception handlers to our

theFutureIsNow

function:

function*

theFutureIsNow

() {

let

data

;

try

{

data

=

yield

Promise

.

all

([

nfcall

(

fs

.

readFile

,

'a.txt'

),

nfcall

(

fs

.

readFile

,

'b.txt'

),

nfcall

(

fs

.

readFile

,

'c.txt'

),

]);
}

catch

(

err

) {

console

.

error

(

"Unable to read one or more input files: "

+

err

.

message

);

throw

err

;

}

yield

ptimeout

(

60

*

1000

);

try

{

yield

nfcall

(

fs

.

writeFile

,

'd.txt'

,

data

[

0

]

+

data

[

1

]

+

data

[

2

]);

}

catch

(

err

) {

console

.

error

(

"Unable to write output file: "

+

err

.

message

);

throw

err

;

}
}

I’m not claiming that

try...catch

exception handling is inherently superior to

catch

handlers on promises, or error-first callbacks, but it is a well-understood mechanism

for exception handling, and if you prefer synchronous semantics, then you will want

to be able to use it for exception handling.

216 | Chapter 14: Asynchronous Programming

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.