39 Matching Annotations
  1. Apr 2022
    1. Because promise handlers aren’t immediately executed, you might imagine that they act a little like timers — giving the browser a chance to repaint and perform other important tasks before the handler is executed.

      is this because callbacks go into the callback queue ie. lower priority than the microtask queue ?

      promises and mutation observer go into the microtask queue and have higher higher priority, are DOM mutations the "important tasks" that James is refering to ??

    2. In fact, promises aren’t like timers at all. If there are any promise handlers waiting to be executed when your script completes, they’ll be executed immediately.

      is this because promises go into the microtask queue ( higher priority than the callback queue ) ??

    3. rejection handler for then()

      this is also applicable tor .catch() . since catch() is just a special case of .then() ie. .then(null , failure handler). Check the description of promise.catch in the "A Spoonful of Sugar" chapter.

  2. Feb 2022
  3. Jan 2022
    1. new Promise(function(resolve, reject) { setTimeout(() => { throw new Error("Whoops!"); }, 1000); }).catch(alert);
    2. we should have the unhandledrejection event handler (for browsers, and analogs for other environments) to track unhandled errors and inform the user (and probably our server) about them, so that our app never “just dies”.
    3. What happens when a regular error occurs and is not caught by try..catch? The script dies with a message in the console. A similar thing happens with unhandled promise rejections.
    1. My gut told me calling an async function from the setTimeout callback was a bad thing. Since the setTimeout machinery ignores the return value of the function, there is no way it was awaiting on it. This means that there will be an unhandled promise. An unhandled promise could mean problems if the function called in the callback takes a long time to complete or throws an error.
    2. The callback executed by setTimeout is not expected to return anything, it just ignores the returned value. Since once you enter the promise/async world in JavaScript you cannot escape, I was left to wonder what happens when the setTimeout callback returns a promise?
    1. test2 being marked async does wrap your return value in a new promise:
    2. const rejectedP = Promise.reject('-'); const finallyP = rejectedP.finally(); const result1 = rejectedP; const result2 = new Promise(resolve => { const rejectedP = Promise.reject('-'); const finallyP = rejectedP.finally(); resolve(rejectedP); }); we can see that the first snippet creates two promises (result1 and rejectedP being the same) while the second snippet creates three promises. All of these promises are rejected, but the rejectedP rejection is handled by the callbacks attached to it, both through ….finally() and resolve(…) (which internally does ….then(resolve, reject)). finallyP is the promise whose rejection is not handled in the both examples. In the second example, result2 is a promise distinct from rejectedP that is also not handled, causing the second event.
    1. You basically did var a = promise.then(…); var b = promise.catch(…); creating a branch in the chain. If promise is getting rejected now, the catch callback will be called and b will be a fulfilled promise just fine, but the a promise is getting rejected too and nobody handles that. Instead, you should use both arguments of then and write Requirement.create({id: id, data: req.body.data, deleted: false}) .then(requirement => { res.json(requirement); }, reason => { let err = {'error': reason}; res.json(err); });
    1. Fundamentally, I think promise rejection is substantially different than "throwing" under normal synchronous flow.
    2. const promise = Promise.reject(new Error("Something happened!")); setTimeout(async () => { // You want to process the result here... try { const result = await promise; console.log(`Hello, ${result.toUpperCase()}`) } // ...and handle any error here. catch (err) { console.error("There was an error:", err.message); } }, 100);
  4. www.npmjs.com www.npmjs.com
    1. Generator based control flow goodness for nodejs and the browser, using promises, letting you write non-blocking code in a nice-ish way.
    1. There are a lot of nasty gotchas with unhandled rejections. That's why Node.js gives you a mechanism for globally handling unhandled rejections.
  5. Jul 2021
    1. “!e ‘projecting’ of‘futurologists’ uses the future as the safest possible context forwhatever is desired; it binds one only to selfish interest. But makinga promise binds one to someone else’s future.”

      This is part of why Mark Zuckerberg's promises to "do better in the future" are wholly unbelievable and disingenuous.

  6. Feb 2021
    1. An async function simply implies that a promise will be returned and if a promise is not returned, JavaScript will automatically wrap it in a resolved promise with the return value in that function. That would look like writing return Promise.resolve(‘hello’)
  7. Oct 2020
    1. Returns a Promise<?Object> that resolves with no value on success or resolves with an Object of submission errors on failure. The reason it resolves with errors is to leave rejection for when there is a server or communications error.
    1. Another example:

      const expensiveOperation = async (value) => {
        // return Promise.resolve(value)
          // console.log('value:', value)
          await sleep(1000)
          console.log('expensiveOperation: value:', value, 'finished')
          return value
      }
      
      var expensiveOperationDebounce = debounce(expensiveOperation, 100);
      
      // for (let num of [1, 2]) {
      //   expensiveOperationDebounce(num).then(value => {
      //     console.log(value)
      //   })
      // }
      (async () => { await sleep(0   ); console.log(await expensiveOperationDebounce(1)) })();
      (async () => { await sleep(200 ); console.log(await expensiveOperationDebounce(2)) })();
      (async () => { await sleep(1300); console.log(await expensiveOperationDebounce(3)) })();
      // setTimeout(async () => {
      //   console.log(await expensiveOperationDebounce(3))
      // }, 1300)
      

      Outputs: 1, 2, 3

      Why, if I change it to:

      (async () => { await sleep(0   ); console.log(await expensiveOperationDebounce(1)) })();
      (async () => { await sleep(200 ); console.log(await expensiveOperationDebounce(2)) })();
      (async () => { await sleep(1100); console.log(await expensiveOperationDebounce(3)) })();
      

      Does it only output 2, 3?

  8. Sep 2020
    1. Your problem is that you were returning the rejected loginDaoCall, not the promise where the error was already handled. loginApi.login(user, password) did indeed return a rejected promise, and even while that was handled in another branch, the promise returned by the further .then() does also get rejected and was not handled.
    2. // LoginApi.js return loginDao.login(username, password).then(function (res) { store.dispatch(loginSuccess()); log.log("[loginApi.login] END"); return true; }, function (err) { store.dispatch(loginFail()); errorUtils.dispatchErrorWithTimeout(errorLogin); log.log(err); return false; }); // never supposed to reject
    1. This treatment of thenables allows promise implementations to interoperate, as long as they expose a Promises/A+-compliant then method. It also allows Promises/A+ implementations to “assimilate” nonconformant implementations with reasonable then methods.
    2. the promise specification explicitly does not make a distinction
    1. This isn't really a bug, because if you have an async function that returns a function, it doesn't really return a function - it returns a promise. I don't remember whether the Svelte internals currently check for the onMount callback's return being a function or whether they check for it being truthy. Maybe there's some adjustment to be made there.
    1. Here we store the three Promise objects in variables, which has the effect of setting off their associated processes all running simultaneously. Next, we await their results — because the promises all started processing at essentially the same time, the promises will all fulfill at the same time
  9. May 2020
  10. developer.mozilla.org developer.mozilla.org
    1. The promises of a chain are nested like Russian dolls, but get popped like the top of a stack.
    2. Similarly, .catch() is really just a .then() without a slot for handleFulfilled.
    3. in the absence of an immediate need, it is simpler to leave out error handling until a final .catch() statement.
    4. Handling a rejected promise too early has consequences further down the promise chain.   Sometimes there is no choice, because an error must be handled immediately.
  11. Mar 2020
    1. The remedy which the tradition of Western thought has proposed for the unpredictability and irreversibility of action has consisted in abstaining from action altogether, in the withdrawal from the sphere of interaction with others, in the hope that one’s freedom and integrity could thereby be preserved. Platonism, Stoicism and Christianity elevated the sphere of contemplation above the sphere of action, precisely because in the former one could be free from the entanglements and frustrations of action. Arendt’s proposal, by contrast, is not to turn one’s back on the realm of human affairs, but to rely on two faculties inherent in action itself, the faculty of forgiving and the faculty of promising. These two faculties are closely connected, the former mitigating the irreversibility of action by absolving the actor from the unintended consequences of his or her deeds, the latter moderating the uncertainty of its outcome by binding actors to certain courses of action and thereby setting some limit to the unpredictability of the future. Both faculties are, in this respect, connected to temporality: from the standpoint of the present forgiving looks backward to what has happened and absolves the actor from what was unintentionally done, while promising looks forward as it seeks to establish islands of security in an otherwise uncertain and unpredictable future.