A
A
Axepec2018-07-31 08:48:11
MySQL
Axepec, 2018-07-31 08:48:11

Node.js, promise, mysql how to return result?

Good afternoon.... I'm trying to figure out node.js promises and asynchrony..

getEmail() {
    let emails = [];
      let result = new Promise( (resolve, reject) => {

        this.start();

        this.db.query('SELECT * FROM contacts', (err, res) => {
          if (!!err) {
            return console.log('Error in the Query');
          } else {

            res.forEach(function (item, i) {
              if ((item.email !== '') && (item.email !== null)) {
                emails.push(item.email);
              }
            });

            resolve( emails );
          }
        });

      });
    
    
    result.then( (result) => {
      this.end();
      console.log('i Work! And I return Result! But i last.....');
      return result;
    });

  }

and when outputting as soon as I did not try
let promise = new Promise( (resolve,reject) => {
  let result = _db.getEmail();
  resolve(result);
});

promise.then( (result) => console.log(result) );

Execution result:
undefined
i Work! And I return Result! But i last.....

That is, the function considers that it is executed, and then the function is executed ....

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladlen Hellsite, 2018-07-31
@Axepec

You've made a lot of sense, it's much easier.

getEmail() {
  return new Promise((resolve, reject) => {
    this.start();

    this.db.query('SELECT * FROM contacts', (err, contacts) => {
      if (err) {
        reject(err);

        return;
      }

      const emails = contacts
        .map(contact => contact.email)
        .filter(Boolean);

      this.end();

      resolve(emails);
    });
  });
}

_db.getEmail()
  .then((emails) => {
    console.log(emails)
  })
  .catch((error) => {
    console.log('Error in the Query', error);
  });

It would be nice to make queries to the database immediately return Promise, then it will become much more convenient.

C
Coder321, 2018-07-31
@Coder321

_getEmail() {
    const emails = [];
    return new Promise((resolve, reject) => {
        this.start();
        this.db.query('SELECT * FROM contacts', (err, res) => {
            if (!!err) {
                return reject('Error in the Query');
            } else {
                res.forEach(function (item, i) {
                    if ((item.email !== '') && (item.email !== null)) {
                        emails.push(item.email);
                    }
                });
                this.end();
                return resolve(emails);
            }
        });

    });
}

async getEmail(){
    try {
        const emails = await this._getEmail();
    } catch (error) {
        console.log(error);
    };
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question