Wrapping Up

JavaScript programs traditionally used callbacks, but that made the code complex and hard to maintain. The promise is an alternative that provides a data channel and an error channel and can be easily composed into a chain of operations. That gives a functional style flavor to code—elegant and easy to work with. The newly introduced async and await builds on promises to bring back familiar imperative code structure while keeping the execution asynchronous.

Exercises

Here are some exercises for you to practice and improve your understanding of promises. You can find answers to these exerciseshere.

Exercise 1

Will Promise.race() wait for at least one of the candidate promises to resolve?

Exercise 2

Will Promise.all() wait for all candidate promises to either resolve or reject?

Exercise 3

Write a program, using promises, that will print the program’s source code. The current filename can be obtained using the variable __filename.

Exercise 4

In Gathering All Promises the numbers.txt file had a few small numbers. Change that file to hold the values 100000 and 500000 on two separate lines. Now, when the program all.js is run, it takes a long time to complete. Modify the code such that if the execution takes more than 1 second the program will time out and exit. Use the createTimeout() function we created in your solution. Remember to leave the count-prime-service.js program running to serve the http call.

Exercise 5

The previous exercise uses promises. Convert the code to use async and await.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.27.58