Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Promise & async await & TypeScript #108

Open
xgqfrms opened this issue May 13, 2024 · 0 comments
Open

Promise & async await & TypeScript #108

xgqfrms opened this issue May 13, 2024 · 0 comments
Labels
async & await & promise async & await & promise async & await & promise async & await & promise LeetCode LeetCode TypeScript TypeScript

Comments

@xgqfrms
Copy link
Owner

xgqfrms commented May 13, 2024

Promise & async await & TypeScript

type P = Promise<number>

async function addTwoPromises(promise1: P, promise2: P): P {
   const [a, b] = await Promise.all([promise1, promise2]);
    return a + b;
    // return Promise.resolve(a + b);
};
// async function addTwoPromises(promise1: P, promise2: P): P {
//     const a = await promise1;
//     const b = await promise2;
//     // const a = await promise1.then(v => v);
//     // const b = await promise2.then(v => v);
//     return Promise.resolve(a + b)
// };

/**
 * addTwoPromises(Promise.resolve(2), Promise.resolve(2))
 *   .then(console.log); // 4
 * 
 */

https://leetcode.com/problems/add-two-promises/?envType=study-plan-v2&envId=30-days-of-javascript

// promise function ⚠️
function resolveAfter2Seconds() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('resolved');
    }, 2000);
  });
}

async function asyncCall() {
  console.log('calling');
  const result = await resolveAfter2Seconds();
  console.log(result);
  // Expected output: "resolved"
}

asyncCall();

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

async function f() {
  // new Promise ✅
  let promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("done!"), 1000)
  });

  let result = await promise; // wait until the promise resolves (*)

  console.log(result); // "done!"
} 

f();

https://javascript.info/async-await

@xgqfrms xgqfrms added async & await & promise async & await & promise async & await & promise async & await & promise TypeScript TypeScript LeetCode LeetCode labels May 13, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
async & await & promise async & await & promise async & await & promise async & await & promise LeetCode LeetCode TypeScript TypeScript
Projects
None yet
Development

No branches or pull requests

1 participant