I need to get all results synchronized and append to a string with async/await keywords like c#
I am new to node.js and i can not adapt this new syntax to my code.
var string1 = '';
var string2 = '';
var string3 = '';
var string4 = '';
DatabasePool.getConnection(function(err, connection) {
connection.query(query,function (err, result) {
if (err){};
string1 = result;
});
connection.query(query,function (err, result) {
if (err){};
string2 = result;
});
connection.query(query,function (err, result) {
if (err){};
string2 = result;
});
connection.query(query,function (err, result) {
if (err){};
string2 = result;
});
// i need to append all these strings to appended_text but
// all variables remain blank because below code runs first.
var appended_text = string1 + string2 + string3 + string4;
});
if you happen to be in Node 8+, you can leverage the native
util.promisify()
with the node mysql.Do not forget to call it with
bind()
so thethis
will not mess up:Assuming that your ORM that you are using it promise-based you can do something like this
Any promise can be used with async/await by putting
await
in front of the call. However, notice that this function must be used within anasync
function "wrapper". You need to handle the errors intry/catch
blocks.I also want to point out that these 4 queries are not run simulatneously. You'll still need to use Promise.all for that.
It seems you use mysqljs which isn't a promised based library. So you can't achieve what you want using this library. So what you can do is use a promised based library like Sequelize or else as a comment suggests:
I don't know much about wrapping thing, so what I did was to switch to the sequelize.
Use mysql2 packet. It has promise wrapper so you can do that:
If you want to use mysql (also called mysqljs) you have to do a little bit of work if you don't want to use a wrapper. But it's easy enough. Here is how the connect function would look like:
As you can see the await will know how to handle a promise. You create such and use the resolve/reject functions in the callback implementation. That's all there is to it, really, so using a wrapper may be a bit much unless you access your database a lot.
You would have to make sure that the mysql library you are using either supports Promises, which are required by
async
/await
, or use a tool like Bluebird'spromisifyAll
to wrap the library.Note that calling
appendedText()
will actually return a Promise and not a value.