Why can’t mistakes be thrown here?

  node.js, question
const promise = new Promise(function (resolve) {
 resolve('ok');
 // setTimeout(function () {
 throw new Error('test');
 // }, 0);
 });
 
 promise.then(console.log);

After the comments are removed, you can

Finally back to school …
What the subject said:

const promise = new Promise(function (resolve) {
 resolve('ok');
 // setTimeout(function () {
 throw new Error('test');
 // }, 0);
 });
 
 promise.then(console.log);

Problem: Cannot throw exception.

Next we analyze several situations and try to explain them.

First, give us a source code address
Portal:https://github.com/then/promi …

function Promise(fn) {
 if (typeof this !  == 'object') {
 throw new TypeError('Promises must be constructed via new');
 bracket
 if (typeof fn !  == 'function') {
 throw new TypeError('Promise constructor\'s argument is not a function');
 bracket
 this._deferredState = 0;
 this._state = 0;
 this._value = null;
 this._deferreds = null;
 if (fn === noop) return;
 doResolve(fn, this);
 bracket
 //In which the thrown error is processed in doResolve (), and the corresponding resolve()/reject () function is called to modify its own state and value/cause

Log out “ok” if setTimeout is commented out.

  1. In the Promise function, doResolve is actually similar to the process in then function and has the characteristics of 2 points, i.e. one time, so after the resolve(“ok “) is called, the state and value have been fixed and passed to then ()

  2. The problem of then function, let’s see what then function is like.promise2 = promise1.then(onFulfilled, onRejected), pass in two functions, on fullfilled and on rejected, and return a promise object. see my blog post for details. now I’ll take out the situation corresponding to the main pass-in function.

  • If onFulfilled is not a function and promise1 status is fulfilled, thenPromise2 status is fulfilledAnd the value is the same as that of promise1Same value

  • If onrejected is not a function and promise1 status is Rejected, thenPromise2 status must be rejected.And with reason of promise1Despite the same reasonsFull stop

  • OnFulfilled and onRejected functions can only be used when the promise state is fulfilled/rejected.Call once

We can see that promise is passed then,then, which only accepts the onFulfilled function, so “ok” appears in the console

Comment out resolve(“ok “) and setTimeout,console has no information

Innew Promise(fn)In order for promise to be generated normally, an error was captured internally. the specific function is as follows

function tryCallTwo(fn, a, b) {
 try {
 fn(a, b);
 } catch (ex) {
 LAST_ERROR = ex;
 return IS_ERROR;
 bracket
 bracket

Promise captured the incoming fn function in error and returned IS_ERROR to indicate that an exception occurred. at this time, the exception has been captured and processed. then according to this exception, our promise status is also determined bypending->rejectedAnd have rejected because ofAbnormal exFull stop

This promise is passed to the then function, however, in our then function onRejected is undefined, so this then function directly returnsNew rejectedWith reasons of rejectionAbnormal exPromise object for(then must return a promise object.)With itsSubsequent treatmentFull stop

Therefore, there is no information generated in the console.

Do not comment on any code, directly execute, console “ok” and then throw an exception

We made it clear why “ok” appeared, and then threw an exception because setTimeout 0 worked.
As we all know, JavaScript on the browser side isSingle threadThe execution of our task is an event loop, the so-called delay, timer, trigger callback are all based on timer, the so-calledTrigger execution is actually an immediate queueJust. when setTimeout is set to 0, it also meansInsert queue now, not immediately, also does not guarantee the execution time, so this is the casesetTimeout(fn,0)In fact, it means not to execute immediately, but to queue up, which is similar to puttingTeaminsideFirst personThrow itEnd of teamYes.
So the anomaly is actuallyThe execution is finished.Promise was thrown after it was built, so “ok” appeared in console and an exception was thrown.

In fact, I am not very clear here either. I hope someone can add something