Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

104
Views
Javascript Promise Callback (when it is called)

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!