tasks :
Write a function to download data from url
Write a function to save the downloaded data in a file and return the file name.
Write a function to upload the file, written in the previous step, to a new URL.
through callback :
function customeFetch(data, fn) {
console.log("starting downloading..");
setTimeout(() => {
console.log("download completed.. ");
let response = "data";
fn(response);
console.log("ending the customeFetch function");
}, 4000);
}
function writeFile(data, fn) {
console.log("starting writting data..", data);
setTimeout(() => {
console.log("writting completed.. ");
let filename = "fileName.txt";
fn(filename);
console.log("writting ended..");
}, 10000);
}
function uploadFile(filename, newUrl, fn) {
console.log("upoading started..");
setTimeout(() => {
console.log(`file ${filename} uploaded succesful on ${newUrl}`);
let uploadResponse = "success";
fn(uploadResponse);
console.log("upload ended..");
}, 10000);
}
customeFetch("www.google.com", (response) => {
console.log("downloaded response is ", response);
writeFile(response, (filenameResponse) => {
console.log("new file written is", filenameResponse);
uploadFile(filenameResponse, "www.drive.google.com", (uploadResponse) => {
console.log("successful uploaded ", uploadResponse);
});
});
});
Explanation: whatever the variables that are declared inside the customFetch or writeFile, or uploadFile functions, those function variables are accessible within the function calls(invoke) due to the concept of closure and lexical scope.