I'm using node.js
and npm's sqlite
package and discord.js
to make a discord bot.
I try to get a array back from a async function containing a sqlite request.
It seems like my sqlite request is also asynchronous cause I get the empty response before the request is executed. How do I have to form my request to get it executed first?
I already read this post: How do I return the response from an asynchronous call? but I still dont get it. It is not a duplicate cause the question in the link is about ajax
and did not help me much. I hope that if I see it with my own code I'm able to understand it better.
This is what I'm having at the moment. I already tried it with callbacks without a result.
Promise approach:
This is my async function in dbHandler.js
.
var Promise = require("bluebird");
getList: function(userID) {
return new Promise(function(resolve, reject) {
var array = [];
sql.each(`SELECT * FROM table WHERE userID = ?`, userID, (err, row) => {
if (err) {
return console.error(err);
} else {
console.log("row: " + row + " element: " + row.username);
array.push(row);
}
});
array.forEach(function(element) {
console.log("element: " + element.username);
});
console.log("array: " + array);
resolve(array);
});
}
And this is my call in list.js
.
db.getList(uid)
.then(function(v) {
console.log("size: " + v.size);
})
.catch(function(v) {
console.log("failed: " + v);
});
In console I get this.
array:
size: undefined
row: [object Object] element: user1
row: [object Object] element: user2
row: [object Object] element: user3
Callback approach:
dbHandler.js
getList: function(userID, callback) {
var array = [];
sql.each(`SELECT * FROM warns WHERE userID = ?`, userID, (err, row) => {
if (err) {
return console.error(err);
} else {
array.push(row);
}
});
if (array) {
callback("", array);
} else {
callback("error", "");
}
},
list.js
db.getList(uid, function (err, response) {
if (err) {
console.log(err);
} else {
console.log(response.size);
}
});
With the callback approach I only get undefined
in console.