abdullateef najem
abdullateef najem

Reputation: 41

how to create promises properly in node.js

I'm working currently on a project and I need to make some functions asynchronously.

I searched for that, and I found that promises will do the work. Here is my code:

var check = `SELECT * FROM change_name_spelling WHERE SID = ${SID}`;
isSIDInDB = false;

let promise1 = new Promise(function(resolve, reject) {
    con.query(check, function callback(err, result) {
        if (err) throw err;
        console.log('length: ' + result.length);

        const error = false;

        if (!error) resolve(result.length);
        else reject('Rejected');

    });

    promise1
        .then(function(value) {
            if (value > 0) {
                isSIDInDB = true;
                console.log('is db, from query, ' + isSIDInDB);
            } else {
                isSIDInDB = false;
                console.log('is Not in db, from query, ' + isSIDInDB);
            }
            resolve(isSIDInDB);
            reject();
        })
        .then(function(value) {
            if (value) {
                console.log('in db');
            } else {
                console.log('not in db');
            }
        });
}).catch(error, function() {
    console.log(error);
});

However, when I run this code, I got these errors:

1- UnhandledPromiseRejectionWarning: ReferenceError: promise1 is not defined.

2- UnhandledPromiseRejectionWarning: Unhandled promise rejection.

3- UnhandledPromiseRejectionWarning: ReferenceError: error is not defined.

please note that I already installed the promise packages in VS code using the command "npm install Promise" but still got the same errors. What shall I do?

Upvotes: 0

Views: 154

Answers (2)

Azer
Azer

Reputation: 1287

1. You have promise1.then(...) in the body of the callback function that is part of promise1 definition, which is why you get ReferenceError. Basically, you're trying to refer to promise1 as you are initializing the variable. Move promise1.then(...) outside of the callback function.

2. You have resolve and reject right after each other on this piece of code here:

resolve(isSIDInDB);
reject();

This reject will never be called since resolve is always called first.

3. You need to pass the error variable to the callback function.

#This is wrong
}).catch(error, function() {
    console.log(error);
});

#This is right
}).catch( function(error) {
    console.log(error);
});

Start by fixing this and see what errors remain.

Also, you might want to read up on promises to understand them better: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Upvotes: 1

Boney
Boney

Reputation: 2202

You are using the promise1 object in the promise constructor function itself. That is the reason for promise1 is not defined error.
Also as mentioned in one of the comments, you shouldn't be using the resolve or reject function inside the then function. Those functions won't even be available once you have correctly created the promise1 object

Please change the code to as below and try once.

var check = `SELECT * FROM change_name_spelling WHERE SID = ${SID}`;
isSIDInDB = false;

let promise1 = new Promise(function (resolve, reject) {
  con.query(check, function callback(err, result) {
    if (err) throw err;
    console.log('length: ' + result.length);

    const error = false;

    if (!error) resolve(result.length);
    else reject('Rejected');
  })
});

promise1.then(function (value) {
  if (value > 0) {
    isSIDInDB = true;
    console.log('is db, from query, ' + isSIDInDB);
  } else {
    isSIDInDB = false;
    console.log('is Not in db, from query, ' + isSIDInDB);
  }
  if (isSIDInDB)
    return isSIDInDB;
  throw new Error(`not found`);
})
  .then(function (value) {
    if (value) {
      console.log('in db');
    } else {
      console.log('not in db');
    }
  }).catch(error, function () {
    console.log(error);
  });

Upvotes: 0

Related Questions