Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Written by Prashant Basnet
š Welcome to my Signature, a space between logic and curiosity.
Iām a Software Development Engineer who loves turning ideas into systems that work beautifully.
This space captures the process: the bugs, breakthroughs, and āahaā moments that keep me building.
š§± 1. Basic Function
function feature(){ return "hi" }Everything here runs top to bottom, line by line, without interruption.
No Delays: Everything executes in order without waiting.
š 2. Dealing with Delayed Work (Asynchronous)
Problem: Fetching data e.g., from a database takes time. If we donāt wait, we might try to use data that isnāt ready yet.
Here we are trying to access firstName of user.
If we log userData.firstName before fetchUser(id) finishes, we risk accessing data that hasn't arrived yet. Similar to:
Uncaught TypeError: Cannot read properties of undefined (reading 'firstName')
Here database fetches are asynchronous and can take time. To ensure the data is ready, we must wait (using await) for the fetch to complete before using the result. This guarantees our app doesnāt break or log undefined.
function feature(){ await fetchDb() }Because JavaScript needs to know in advance that your function will deal with asynchronous code. If you donāt declare the function as async, it has no idea it needs to pause and wait.
ā Fix: Tell JavaScript itās an async job
async function feature(){ await fetchDb(); // ā Now JavaScript knows to wait here }Await only works inside async functions because JavaScript must prepare to pause and resume execution and it can only do that inside an async context.
Diving Deep into Async/Await:
Even though you donāt return anything explicitly, an async function always returns a Promise.
With Return:
async function orderingFood(){ return "delivery started" }orderingFood() returns: Promise {<fulfilled>: 'delivery started'}No Return:
async function feature() { // No return }feature() returns: Promise {<fulfilled>: undefined}What is a Promise?
A Promise is a placeholder for a value that will be available later (asynchronous work).
States of Promise:
new Promise((resolve, reject) => { if(something goes as expected) { resolve(it) }else{ reject(it) } })Once my mentor told me that Async is the sugar coated form of promise!
function fetchUser(){ return new Promise((resolve, reject) =>{ setTimeout(() => { resolve({name: "prashant"}) }, 1000) // ā±ļø simulating delay }) }fetchUser().then( user => { console.log(user.name) // "Prashant" })š Here, weāre manually handling .then() to wait for the Promise to resolve.
Sugar coated with Async/Await:
async function feature(){ const user = await fetchUser(); // ā³ Waits here console.log(user.name); // ā Now it's safe }Working with promises:
Given two promises promise1 and promise2, return a new promise.
promise1 and promise2 will both resolve with a number. The returned promise should resolve with the sum of the two numbers.
Example 1:
Code:
async function addTwoPromises(promise1, promise2){ return new Promise((resolve, reject) => { Promise.all([promise1, promise2]) .then([one, two] => { resolve(one + two) }) .catch(err => reject(err)) }) }async function addTwoPromises(promise1, promise2){ let one = await promise1 let two = await promise2 return one + two }Given an asynchronous function fand a time t in milliseconds, return a new time limited version of the input function. takes arguments provided to the time limited function.
The time limited function should follow these rules:
Example 1:
Input: fn = async (n) => { await new Promise(res => setTimeout(res, 100)); return n * n; } inputs = [5], t = 50Output: {"rejected":"Time Limit Exceeded","time":50}Explanation:
const limited = timeLimit(fn, t)
const start = performance.now()
let result;
try {
const res = await limited(...inputs)
result = {"resolved": res, "time": Math.floor(performance.now() - start)};
} catch (err) {
result = {"rejected": err, "time": Math.floor(performance.now() - start)};
}
console.log(result) // Output
The provided function is set to resolve after 100ms. However, the time limit is set to 50ms. It rejects at t=50ms because the time limit was reached.
var timeLimit = function (fn, t) { return async function (...args) { return Promise.race([ fn(...args), new Promise((resolve, reject) => setTimeout(() => reject("Time Limit Exceeded"), t)) ]) } };