lab3 ‐ Asynchronous Programming – Promises - isel-leic-pi/IPW-2627i-LEIRT31D GitHub Wiki
Asynchronous Programming – Promises
Exercise 1 - File System with Promises (Node.js)
Using the Node.js Promises API for file access, complete the tasks described below.
You must implement two separate functions, each with a clear and well-defined responsibility.
Function 1 - readAndFilter()
Implement a function called readAndFilter() that does the following:
- Reads the liga.json file using
fs.promises.readFile. - Parses the file contents from JSON into a JavaScript object or array using the
JSON.parsefunction. - Filters the teams and returns only those whose number of goals scored (
goals) is greater than 10. - Returns the filtered array.
Function 2 - saveResult(filteredTeams)
Implement a function called saveResult() that:
- Receives the filtered array returned by
readAndFilter(). - Converts this array into formatted JSON using
JSON.stringify(filteredTeams). - Writes the result to a new file called
liga10goals.jsonusingfs.promises.writeFile.
Final Goal
Create a small main() function (or similar control code) that:
- Calls
readAndFilter()to obtain the filtered teams. - Passes the result to
saveResult().
When executed, the program should produce the file:
liga10goals.json
containing only the teams that scored more than 10 goals.
Example Result (inside liga10goals.json)
[
{
"name": "Benfica",
"goals": 12,
"points": 30
},
{
"name": "Porto",
"goals": 15,
"points": 28
},
{
"name": "Sporting",
"goals": 11,
"points": 27
}
]
Exercise 2 - Fetch API (Node.js)
Using the Fetch API, write a program that retrieves information about animated movies from a web API and saves the titles of all movies to a local JSON file.
You must implement two separate functions, each with a clear and well-defined responsibility.
Function 1 - fetchMovies()
Implement a function called fetchMovies() that does the following:
Makes an HTTP GET request to:
https://api.sampleapis.com/movies/animation
- Uses the Fetch API to retrieve the data.
- Parses the response as JSON using
response.json(). - Extracts only the titles of the movies from the returned objects.
- Returns an array of movie titles.
Function 2 - saveTitles(titles)
Implement a function called saveTitles() that:
- Receives the array of movie titles returned by
fetchMovies(). - Converts the array into formatted JSON using:
JSON.stringify(titles, null, 2)
Saves this JSON to a file called:
animationTitles.json
using fs.promises.writeFile.
Final Goal
Write a small main() function (or similar) that:
- Calls
fetchMovies()to obtain the titles. - Passes the result to
saveTitles().
When executed, the program should create the file:
animationTitles.json
containing all the movie titles retrieved from the API.
Example Result (inside animationTitles.json)
[
"Spirited Away",
"Toy Story",
"How to Train Your Dragon",
"Zootopia"
]
The actual titles will depend on the API response.