Here are the solutions to the Exercises, for the Chapter 10, Keeping Your Promises chapter.
No. Promise.race() will complete with the state of the first promise to complete. If the first resolves, then race() will resolve. If the first rejects, so will race().
No. If any of the candidate promise rejects, then all() will reject. However, if no candidate promise has rejected, then all() will resolve when all candidate promises resolve.
| /* |
| npm install fs-extra |
| */ |
| |
| 'use strict'; |
| |
| const fs = require('fs-extra'); |
| |
| fs.readFile(__filename) |
| .then(contents => console.log(contents.toString())) |
| .catch(err => console.log(err.message)); |
| 'use strict'; |
| |
| const fs = require('fs-extra'); |
| const request = require('request-promise'); |
| |
| const countPrimes = function(number) { |
| if(isNaN(number)) { |
| return Promise.reject(`'${number}' is not a number`); |
| } |
| |
| return request(`http://localhost:8084?number=${number}`) |
| .then(count => `Number of primes from 1 to ${number} is ${count}`); |
| }; |
| |
| const createTimeout = function(timeInMillis) { |
| return new Promise(function(resolve, reject) { |
| setTimeout(() => reject(`timeout ${timeInMillis} MS`), timeInMillis); |
| }); |
| }; |
| |
| const logAndTerminate = function(err) { |
| console.log(err); |
| process.exit(1); |
| }; |
| |
| const countPrimesForEachLine = function(pathToFile) { |
| fs.readFile(pathToFile) |
| .then(content => content.toString()) |
| .then(content =>content.split('n')) |
| .then(lines => Promise.race( |
| [Promise.all(lines.map(countPrimes)), createTimeout(1000)])) |
| .then(counts => console.log(counts)) |
| .catch(logAndTerminate); |
| }; |
| |
| countPrimesForEachLine('numbers.txt'); |
| 'use strict'; |
| |
| const fs = require('fs-extra'); |
| const request = require('request-promise'); |
| |
| const countPrimes = function(number) { |
| if(isNaN(number)) { |
| return Promise.reject(`'${number}' is not a number`); |
| } |
| |
| return request(`http://localhost:8084?number=${number}`) |
| .then(count => `Number of primes from 1 to ${number} is ${count}`); |
| }; |
| |
| const createTimeout = function(timeInMillis) { |
| return new Promise(function(resolve, reject) { |
| setTimeout(() => reject(`timeout ${timeInMillis} MS`), timeInMillis); |
| }); |
| }; |
| |
| const logAndTerminate = function(err) { |
| console.log(err); |
| process.exit(1); |
| }; |
| |
| const readFileContents = function(pathToFile) { |
| return fs.readFile(pathToFile) |
| .then(content => content.toString()) |
| .then(content =>content.split('n')); |
| } |
| |
| const countPrimesForEachLine = async function(pathToFile) { |
| try { |
| const lines = await readFileContents(pathToFile); |
| |
| const counts = await Promise.race( |
| [Promise.all(lines.map(countPrimes)), createTimeout(1000)]); |
| |
| console.log(counts); |
| } catch(err) { |
| logAndTerminate(err); |
| } |
| }; |
| |
| countPrimesForEachLine('numbers.txt'); |
3.147.193.3