Answer the question
In order to leave comments, you need to log in
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;
});
}
let promise = new Promise( (resolve,reject) => {
let result = _db.getEmail();
resolve(result);
});
promise.then( (result) => console.log(result) );
undefined
i Work! And I return Result! But i last.....
Answer the question
In order to leave comments, you need to log in
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);
});
_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 questionAsk a Question
731 491 924 answers to any question