Where does Promise executor callback live when asynchronous code is being run?

爱⌒轻易说出口 提交于 2020-05-17 03:04:15

问题


A Promise constructor function can take a executor callback function and this question is about where does that callback function live in execution space when the executor callback function has asynchronous code.

DETAILS :

A Promise object represents a value that may not be available yet, but will be resolved at some point in the future. It allows you to write asynchronous code like making a call to a remote web service, you will create a Promise object which represents the data that will be returned by the web service in future.

Until the actual data is available, the Promise object acts like a proxy to the actual data.

Code snippet below depicts this situation :

function getRandomJoke(){
  return new Promise((resolve, reject) => {
    const request = new XMLHttpRequest();

    request.open('GET', 'https://api.icndb.com/jokes/random');
    request.onload = () => {
      if (request.status === 200) {
        resolve(request.response); // we got data here, so resolve the Promise
      } else {
        reject(Error(request.statusText)); // status is not 200 OK, so reject
      }
    };

    request.onerror = () => {
      reject(Error('Error fetching data.')); // error occurred, reject the  Promise
    };

    request.send(); // send the request
  });
}

As per the discussion in this thread, both Promise creation and executor callback function execution happens on the main thread and only resolve callback will be executed on the next tick of event loop.

If that is the case, above code snippet's executor function has asynchronous code of making API call - will that also hang on to the main thread till API returns data.


回答1:


If that is the case, above code snippet's executor function has asynchronous code of making API call - will that also hang on to the main thread till API returns data.

No, it won't hang anything. request.send() is asynchronous and non-blocking. When you call request.send() it initiates the sending of the request (turns it over to the OS) and then immediately returns. The promise executor function itself returns and then the main thread is free to do whatever else it wants to do.

Meanwhile, sometime later, the underlying TCP operation will cause an event to get inserted into the event queue. When that event gets processed by the main thread (when it's not doing anything else and this event gets its turn in the event queue), the request object will then generate either an onload or an onerror event and the corresponding listener will resolve or reject the promise. That will set in motion the promise calling it's .then() or .catch() handlers on a future tick.

Using request this way is absolutely no different inside a promise executor function as it is anywhere else in node.js. It initiates the asynchronous, non-blocking operation, you set up some listeners for callbacks and then the nodejs interpreter is free to do other things until sometime later when a completion event occurs and some callbacks get called.

Where does Promise executor callback live when asynchronous code is being run?

It's not super clear what you mean by "where does it live?". The promise executor function is just like any other function. It's called synchronously and when it returns the new Promise() constructor returns and there's a promise created that the calling code can use. Sometime later that promise will get resolved or rejected (usually). Part of initializing and setting up the promise is running of the promise executor function, but that's just one step in creating the promise. That function doesn't block if you happen to do something asynchronous in it.



来源:https://stackoverflow.com/questions/61671321/where-does-promise-executor-callback-live-when-asynchronous-code-is-being-run

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!