Reputation: 373
I am using nodejs with serverless, trying to query to mysql
module.exports.message = (event, context, callback) => {
const { content } = event;
let search = new Shop();
console.log('start');
search._search(content, (data) => {
console.log(callback);
callback(null, data);
});
console.log('finish');
});
In shop class,
class Shop{
_search(text, unit = false, callback){
return this._morphs(text).then(function(data){
return data;
})
}
_morphs(text, callback){
return new Promise((resolve, reject) => {
let result = text.split(" ");
let query = `SELECT * from shop where name LIKE CONCAT('%', ?, '%')`;
console.log(1);
for(let i = 0; i < result.length; i++){
DB.query(query, result[i], function (data, error) {
console.log(2);
resolve(data);
});
}
});
}
}
When I execute this,
start 1 finish 2 callback
This is what I had on the log. I want to execute callback before finish. so This code can return the data.
I'm using below mysql moudle. https://www.npmjs.com/package/mysql
Thanks in advance!!
Upvotes: 0
Views: 230
Reputation: 26
Javascript by default is synchronous, but when you write asynchronous (callback/ promise / async) code you need to handle it properly.
In your code, there is 2 issues
module.exports.message =
function console.log('finish') will not wait for search._search
.Db.query
, your resolving promise in each iteration.This should work =>
const { promisify } = require('util'); // Node >=8 or use blubird
promise library promisify
const dbQueryPromise = promisify(DB.query)
class Shop{
_search(text, unit = false){
return this._morphs(text);
}
async _morphs(text){
const result = text.split(" ");
const query = `SELECT * from shop where name LIKE CONCAT('%', ?, '%')`;
console.log(1);
const queryResult = []
for(let i = 0; i < result.length; i++){
const data = await dbQueryPromise(query, result[i])
queryResult.push(data);
}
}
}
module.exports.message = (event, context, callback) => {
const { content } = event;
let search = new Shop();
console.log('start');
search._search(content)
.then((data) => {
console.log(callback);
callback(null, data)
})
.catch(err => {
console.log(callback);
callback(err);
})
.finally(() => {
console.log('finish');
})
});
Upvotes: 1