How does Promise work under the hood

Tell us what’s happening:
i know for sure that javascript and NodeJS is a single threaded language; but how does promise work if it is a single threaded? my intuitive notions tells me that a notification such as a promise should be opened in an independent thread and when it receives the notification it notifies the main and closes that thread. so how does it work under the hood here?

Your code so far


const makeServerRequest = new Promise((resolve, reject) => {
// responseFromServer is set to false to represent an unsuccessful response from a server
let responseFromServer = false;
  
if(responseFromServer) {
  resolve("We got the data");
} else {  
  reject("Data not received");
}
});

makeServerRequest.then(result => {
console.log(result);
});

makeServerRequest.catch(error => {
console.log(error);
})

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36.

Challenge: Handle a Rejected Promise with catch

Link to the challenge:


1 Like

Googling “promises in a single-thread language” turns up this: https://softwareengineering.stackexchange.com/questions/377815/how-does-js-promises-works-being-single-threaded

1 Like