Created
May 18, 2021 14:36
-
-
Save rajivnarayana/932e51c0b202d9a33e6b85367434d115 to your computer and use it in GitHub Desktop.
Javascript - Async, Await, Promises
This file contains 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
const fs = require("fs"); | |
const path = "./temp.txt"; | |
const errorCallback = (err) => { | |
console.log(err); | |
console.log("Failed writing to the files"); | |
} | |
const doneCallback2 = (err) => { | |
if(err) { | |
errorCallback(err); | |
} else { | |
console.log("Wrote to the file temp2 successfully"); | |
} | |
} | |
const doneCallback = (err) => { | |
if (err) { | |
errorCallback(err); | |
} else { | |
console.log("Wrote to the file successfully"); | |
console.log("Step 2. Write to temp2.txt"); | |
fs.writeFile("./temp1.txt", "Hello world "+ new Date(),doneCallback2 ) | |
} | |
}; | |
console.log("Step 1. Write to temp.txt"); | |
fs.writeFile(path, "Hello world "+ new Date(), doneCallback); | |
This file contains 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
const fs = require("fs"); | |
function main() { | |
try { | |
console.log("Writing to file 1"); | |
fs.writeFileSync("./temp.txt", "Hello World "+new Date()); | |
console.log("Wrote to file 1 successfully"); | |
console.log("Writing to file 2"); | |
fs.writeFileSync("./temp2.txt", "Hello World "+new Date()); | |
console.log("Wrote to file 2 successfully"); | |
} catch (err) { | |
console.log(err); | |
console.log("Failed writing to the files"); | |
} | |
} | |
main(); | |
console.log("After main"); |
This file contains 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
const fs = require("fs"); | |
const writeFilePromise = async (filePath, data) => { | |
return new Promise((resolve, reject) => { | |
fs.writeFile(filePath, data, (err) => { | |
if (err) { | |
reject(err); | |
} else { | |
resolve(); | |
} | |
}) | |
}) | |
} | |
async function main() { | |
try { | |
console.log("Writing to file 1"); | |
await writeFilePromise("./temp.txt", "Hello World "+new Date()); | |
console.log("Wrote to file 1 successfully"); | |
console.log("Writing to file 2"); | |
await writeFilePromise("./temp2.txt", "Hello World "+new Date()); | |
console.log("Wrote to file 2 successfully"); | |
} catch (err) { | |
console.log(err); | |
console.log("Failed writing to the files"); | |
} | |
} | |
main(); | |
console.log("After main"); |
This file contains 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
const fs = require("fs").promises; | |
async function main() { | |
try { | |
console.log("Writing to file 1"); | |
await fs.writeFile("./temp.txt", "Hello World "+new Date()); | |
console.log("Wrote to file 1 successfully"); | |
console.log("Writing to file 2"); | |
await fs.writeFile("./temp2.txt", "Hello World "+new Date()); | |
console.log("Wrote to file 2 successfully"); | |
} catch (err) { | |
console.log(err); | |
console.log("Failed writing to the files"); | |
} | |
} | |
main(); | |
console.log("After main"); |
This file contains 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
const fs = require("fs/promises"); | |
/** | |
* Returns a promise that resolves after n seconds. | |
* @param {number} n The no of seconds to wait | |
* @returns Promise<void> | |
*/ | |
async function wait(n = 1) { | |
return new Promise(resolve => setTimeout(resolve, n * 1000)) | |
} | |
function logTime() { | |
console.log(new Date().toLocaleDateString('en-US', {second: '2-digit'})); | |
} | |
async function _main() { | |
logTime(); | |
// await wait(); | |
// await Promise.all([wait(), wait(), wait(), wait(), wait()]) | |
for (let i = 0; i < 5; i++) { | |
await wait(); | |
} | |
logTime(); | |
} | |
async function main() { | |
const query = { name: "rajiv"}; | |
const users = await Users.find(query).exec(); | |
if (users.length == 0) { | |
throw new Error("No user can be found with the given name"); | |
} | |
const [user] = users; | |
// const posts = await Posts.find({"userId": user.id}).exec(); | |
// const comments = await Comments.find({"userId": user.id}).exec(); | |
const [posts, comments ] = await Promise.all([ | |
Posts.find({"userId": user.id}).exec(), | |
Comments.find({"userId": user.id}).exec() | |
]); | |
return { posts, comments }; | |
} | |
main(); |
This file contains 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
function logTime() { | |
console.log(new Date().toLocaleDateString('en-US', {second: '2-digit'})); | |
} | |
async function wait(n = 1) { | |
return new Promise(resolve => setTimeout(resolve, n * 1000)) | |
} | |
async function getData(userId) { | |
await wait(); | |
return { name : "Name "+ userId}; | |
} | |
const timeout = 3000; | |
async function getDataWithTimeout(userId) { | |
return new Promise((resolve, reject) => { | |
let promisePending = true; | |
const timeoutCallback = () => { | |
if (promisePending) { | |
reject(new Error("Timed out")); | |
promisePending = false; | |
} | |
} | |
setTimeout(timeoutCallback, timeout); | |
http.get("url", (err, response) => { | |
if (!promisePending) { | |
return; | |
} | |
promisePending = false; | |
if (err) { | |
reject(err); | |
} else { | |
resolve(response); | |
} | |
}) | |
}) | |
} | |
async function main() { | |
const userIds = [2, 4, 7]; | |
logTime(); | |
const data = await getData(2); | |
// const data = await Promise.all(userIds.map(userId => getData(userId))); | |
console.log(JSON.stringify(data)); | |
logTime(); | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment