0

This is a stupid question but I'm having a hard time understanding how functions are first-class citizens in javascript and when callbacks are called.

const promise = new Promise((resolve,reject) => {
    const error = false
    if(!error) {
        resolve("Promise resolved")
    } else {
        reject("Promise is rejected")
    }

})
console.log(promise) //Promise { 'Promise resolved' }

For the code above why does the callback inside the promise (resolve, reject) => {} get called when I create a Promise? Is this something in the constructor of the Promise class? I cannot understand why it is being called immediately.

mendokusai
  • 165
  • 1
  • 3
  • 13

1 Answers1

1

The promise executor function is called immediately by the promise constructor. That's how it works. The usual point of that executor function is to initiate your asynchronous operation and then later when that asynchronous operation completes, you call resolve() or reject().

Here's an example of putting the plain callback version of fs.readFile() in a promise wrapper:

function readFilePromise(filename, options) {
    return new Promise((resolve, reject) => {
        fs.readFile(filename, options, (err, data) => {
            if (err) {
                reject(err);
            } else {
                resolve(data);
            }
        })
    });
}

Usage:

 readFilePromise("myfile.txt").then(data => {
     console.log(data);
 }).catch(err => {
     console.log(err);
 });

Note: This is just an example for illustration here. Nodejs now already has promisified versions of fs.readFile called fs.promises.readfile, but this structure can be used when you need to manually promisify other more complicated things that don't have their own promise interface yet.


For a real world example of promisifying something more complicated see the mapConcurrent() function here or the rateLimitMap() function here.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Thank you for answering. So there exists a constructor where inside the promise something like ```constructor(executor) {executor()} correct?``` – mendokusai Feb 06 '22 at 20:00
  • 1
    @mendokusai - Yes, that would be part of the constructor implementation. It's a little more involved than that, but that's the general idea. – jfriend00 Feb 06 '22 at 20:02
  • thank you for answering in detail my simple question – mendokusai Feb 06 '22 at 20:03