Synchronous Functions
Asynchronous Functions
Wrapper built on top of async code. There are three states of a wrapper
pending : still working.fulfilled : completed successfully (resolved).rejected : failed (error).function AryanReadFile() {
return new Promise(function(resolve) {
fs.readFile("a.txt", "utf-8", function(err, data) {
resolve(data);
});
})
}
When a promise is made, the .then() attribute is used to fulfill the promise.
function onCompletion(data) {
console.log(data);
}
AryanReadFile().then(onCompletion);
The syntax of this is very jarring to understand and complex which is why people use async and await functions now.
function hi() {
let p = new Promise(function (resolve){
resolve("\\n\\nhi there!")
});
return p;
}
async function main() {
const value = await hi();
console.log(value)
}
main();
Here, a promise p has been made which is present in an asynchronous function main. We await at the promise so that the code doesn’t keep the promise pending. Await is to hold the async function it’s like a red light signal that says, “Bhai tu ye kaam pehle kar aur fir baakika kar asynchronously.”
Returning a promise to make sure callback has been made.
function promisifiedMyOwnSetTimeout(duration) {
const p = new Promise(function(resolve) {
setTimeout(function() {
console.log("Hi there this is happening inside the promise.");
}, duration);
});
return p;
}
const ans = promisifiedMyOwnSetTimeout(1000);
ans.then(function() {
console.log("timeout is done!");
});