Thursday, January 19, 2023

Promise and asynchronous Javascript

You can use the Promise object to return a setTimeout and resolve inside it. Here's an example:


Copy code

function waitAndResolve(ms) {

  return new Promise((resolve) => {

    setTimeout(() => {

      resolve();

    }, ms);

  });

}

You can then use the waitAndResolve function like this:


Copy code

waitAndResolve(2000).then(() => {

  console.log("2000 milliseconds have passed!");

});

This will wait for 2000 milliseconds and then resolve the promise, which will cause the message "2000 milliseconds have passed!" to be logged to the console.





Pessimist Kai

Hi

Hello! How can I help you today?





Pessimist Kai

currently my function is like this


"f1(){

f2();

f3();

}"

If you want to make sure that f2() and f3() are called in a specific order, you can make use of JavaScript's async/await feature. Here's an example:


Copy code

async function f1() {

  await f2();




Pessimist Kai

I want to run some logic when f2() and f3() are completed

You can use the .then() method on the returned promise of f2() and f3() or use the await keyword with the function call inside an async function to run some logic after f2() and f3() are completed.


Copy code

async function f1() {

  await f2();

  await f3();

  console.log("Both f2 and f3 are completed");

}

or


Copy code

function f1() {

  f2().then(f3).then(()=>{

    console.log("Both f2 and f3 are completed");

  })

}

In this example, the message "Both f2 and f3 are completed" will be logged to the console after both f2() and f3() have completed their execution.





Pessimist Kai

but I don't want f3() to run after f2(), can't they run parallely?

Yes, you can run f2() and f3() in parallel by using Promise.all() method.


Copy code

function f1() {

  Promise.all([f2(), f3()]).then(()=>{

    console.log("Both f2 and f3 are completed");

  });

}

The Promise.all() method takes an array of promises as an argument and returns a new promise that is fulfilled with an array of the fulfilled values of the original promises, in the same order as the original promises, if all of the original promises are fulfilled.


This way, f2() and f3() will run in parallel and the code inside the .then() callback will be executed after both of them are completed.





Pessimist Kai

but f2() and f3() don't return promise they just do some work and api call

If f2() and f3() are not returning promises, you can wrap them in a new promise, so you can use them with Promise.all() and async/await .


Copy code

function f1() {

  Promise.all([

    new Promise(resolve => f2().then(resolve)),

    new Promise(resolve => f3().then(resolve))

  ]).then(() => {

    console.log("Both f2 and f3 are completed");

  });

}

or


Copy code

async function f1() {

  await Promise.all([

    new Promise(resolve => f2().then(resolve)),

    new Promise(resolve => f3().then(resolve))

  ]);

  console.log("Both f2 and f3 are completed");

}

This way, f2() and f3() will run in parallel and the code inside the .then() callback or the line after await will be executed after both of them are completed.


Alternatively, you can make f2() and f3() return a promise, so you can use them directly with Promise.all() and async/await.





Pessimist Kai

new Promise(resolve => f2().then(resolve)) and

new Promise(resolve => f2(resolve)); same?

How?

new Promise(resolve => f2().then(resolve)) and new Promise(resolve => f2(resolve)) are not the same.


The first one is creating a new promise and passing a resolve function to it, then calling f2() and chaining a .then() method on it, passing the resolve function as a callback. This means that the new promise will be resolved with the value returned by f2().


The second one is creating a new promise and passing the resolve function directly to f2(). This means that f2() is responsible for resolving the promise, and it's unclear when or if it will be resolved.


Here's an example of how to use the second approach to make f2() return a promise:


Copy code

function f2(resolve) {

  // Do some work and api call

  // ...

  // Once the work is done, call resolve

  resolve();

}

and then you can use it like:


Copy code

const f2Promise = new Promise(resolve => f2(resolve));

In summary, the first approach returns a promise that is resolved with the value returned by f2() and the second approach requires f2() to resolve the promise.





Pessimist Kai

remind me how promise works again, please

A promise is a JavaScript object that represents the eventual completion (or failure) of an asynchronous operation, and its resulting value. Promises provide a way to register callbacks to be called when the asynchronous operation completes (or fails) and to handle errors.


Promises have three states:


pending: initial state, neither fulfilled nor rejected.

fulfilled: meaning that the operation completed successfully.

rejected: meaning that the operation failed.

A promise is said to be settled if it is either fulfilled or rejected.


Promises are used for handling asynchronous operations in JavaScript, such as making HTTP requests, reading from a file, waiting for a timer to complete, etc. The main advantage of promises over traditional callback-based code is that they make it easier to handle errors and to compose multiple asynchronous operations.


A promise can be created using the Promise constructor, which takes a single argument: a function called the "executor". The executor function is passed two arguments: a resolve function, which is used to resolve the promise with a value, and a reject function, which is used to reject the promise with a reason (an error).


Once a promise is resolved or rejected, it can't change its state anymore.


Copy code

const promise = new Promise((resolve, reject) => {

  // Do some asynchronous operation

  if (/* the operation was successful */) {

    resolve(/* some value */);

  } else {

    reject(/* some reason */);

  }

});

Promises also have methods, such as .then(), .catch(), .finally() and Promise.all(), Promise.race() etc, which can be used to register callbacks and handle errors.


.then() is used to register a callback that will be called when the promise is fulfilled, with the fulfilled value as an argument.

.catch() is used to register a callback that will be called when the promise is rejected, with the rejection reason as an argument.

.finally() is used to register a callback that will be called when the promise is settled (fulfilled or rejected)

Promise.all() is used to wait for multiple promises to settle and return an array of the fulfilled values in the same order as the original promises, if all of the original promises are fulfilled.

Promise.race() is used to wait for one of multiple promises to settle, and return the value of the first promise that settles.


Promises in JavaScript are a powerful tool to deal with asynchronous operations and they are a standard feature of JavaScript since ECMAScript 6.


#promise

Wednesday, January 18, 2023

TIL

 https://stackoverflow.com/questions/64567979/how-to-add-custom-css-to-the-single-toast-message-in-angular

F1 - Disable Javascript

URL- Start with hash

single and double quotes JS

Css selectors:- a.t2 //get all anchor with t2 class
-----------------------------------------------

https://stackoverflow.com/questions/48869187/use-cloudblob-existsasync-vs-catch-storageexception-blobnotfound-in-terms-of-pe
-----------------------------------

Friday, January 13, 2023

BITWISE Operators

Setting a bit: To set a specific bit in a number to 1, you can use the bitwise OR operator (|) with a value that has only that bit set. For example, to set the 3rd bit of a number to 1:

num = num | (1 << 3);

Clearing a bit: To clear a specific bit in a number (set it to 0), you can use the bitwise AND operator (&) with a value that has all bits set except for the target bit. For example, to clear the 2nd bit of a number:

num = num & ~(1 << 2);

Toggling a bit: To toggle (flip) a specific bit in a number, you can use the bitwise XOR operator (^) with a value that has only that bit set. For example, to toggle the 4th bit of a number:

num = num ^ (1 << 4);

Checking a bit: To check if a specific bit in a number is set, you can use the bitwise AND operator (&) with a value that has only that bit set. If the result is not zero, then the bit is set. For example, to check if the 5th bit of a number is set:

if ((num & (1 << 5)) != 0) {

    // 5th bit is set

} else {

    // 5th bit is not set

}

Counting set bits: To count the number of bits set to 1 in a number, you can use the trick called "Brian Kernighan's Algorithm" which is an efficient way of counting set bits in a number, It basically flips the last set bit of the number to 0 and count the times you have to do it to reach 0.

int countOnes(uint n) {

    int count = 0;

    while (n > 0) {

        n &= (n-1);

        count++;

    }

    return count;

}

Get the least significant bit: To get the least significant bit (LSB) of a number, you can use the bitwise AND operator (&) with the number 1. For example, to get the LSB of a number:

int lsb = num & 1;