Created
March 21, 2021 05:54
-
-
Save fernyb/2a0da1ad2214a05775034544437405ba to your computer and use it in GitHub Desktop.
JavaScript Promises
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
(() => { | |
function makeHttpRequests() { | |
let newCount = 0; | |
let a = new Promise((resolve) => { | |
setTimeout(function() { | |
resolve(newCount += 1); | |
}, Math.floor(Math.random() * 10) * 2000); | |
}); | |
let b = new Promise((resolve) => { | |
setTimeout(function() { | |
resolve(newCount += 1); | |
}, Math.floor(Math.random() * 10) * 2000); | |
}); | |
let c = new Promise((resolve) => { | |
setTimeout(function() { | |
resolve(newCount += 1); | |
}, Math.floor(Math.random() * 10) * 2000); | |
}); | |
return Promise.all([a, b, c]).then((results) => { | |
newCount = results.length; | |
console.log(results); | |
console.log("*** New Count: ", newCount); | |
console.log("***************************"); | |
return results; | |
}); | |
} | |
console.log("1. visit web page\n"); | |
function getPersonName(personId) { | |
return makeHttpRequests().then((results) => { | |
let person = { id: results.length, name: "Fern" }; | |
console.log("------------------------------") | |
console.log("0. The Http Results: ", results.length); | |
console.log("------------------------------") | |
return [person, results] | |
}).then(([person, results]) => { | |
newCount = results.length; | |
newCount += 1; | |
return [person, newCount, "new results to send"]; | |
}).then(([person, newCount, message]) => { | |
console.log("------------------------------") | |
console.log("1. Person id: ", person.id); | |
console.log("1. Person object:", person); | |
console.log("------------------------------"); | |
return person; | |
}).then(({ name }) => { | |
console.log("------------------------------"); | |
console.log("2. The person name is: ", name); | |
console.log("------------------------------"); | |
return name; | |
}).then((name) => { | |
console.log("------------------------------"); | |
console.log("3. The Name is: ", name); | |
console.log("------------------------------"); | |
return [personId, name]; | |
}); | |
} | |
const person_id = 1000; | |
getPersonName(person_id).then(([personId, personName]) => { | |
console.log("------------------------------"); | |
console.log("4. getPersonName Id:", personId); | |
console.log("4. getPersonName Name", personName); | |
console.log("------------------------------"); | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment