0

I have a hard time being able to chain functions in node.js, i can't get the receiver to wait. Shouldn't promises be asynchronous and therefore suited for such a task?

const promise = new Promise((resolve, reject) => {
  var input = 'SELECT * FROM ideas;';
  connection.query(input, (err, results) => {
    if(err) {
      console.log(err);
      reject();
    } else {
      console.log('success');
      results = JSON.stringify(results);
      console.log(results);
      resolve();
      return results;
    }
  })
});

promise.then(function(results) {
  results = JSON.parse(results);
  console.log(results);
});

I hope someone knows what I am missing here and can help!

1
  • FYI, if you install and use require('mysql2/promise');, then you can use built-in promise support with your database rather than manually promisifying each operation. Commented Jan 31, 2020 at 15:26

2 Answers 2

1

You only need to add results to resolve and err to reject.

For an example, you can use this code below:

const promise = new Promise((resolve, reject) => {
  var input = 'SELECT * FROM ideas;';
  connection.query(input, (err, results) => {
    if(err) {
      reject(err);
    } else {
      console.log('success');
      results = JSON.stringify(results);
      console.log(results);
      resolve(results);
    }
  })
});

promise.then(function(results) {
  results = JSON.parse(results);
  console.log(results);
}).catch(error => {
  console.log(error);
})
Sign up to request clarification or add additional context in comments.

Comments

0

Send some data back in the reject() or the resolve() statement, Currently you are expecting some results but noting is being sent back. Just convert your Reject and Resolve statement like this: resolve(results); reject(err);

An Extra tip, also chain a catch block with the promise.then call so that exceptions are also handled successfully. as following promise.then(function() { //code if promise resolves }).catch(function(){ //code if promise rejects });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.