I would like to replace some text in a string with values from a database using pg-promise
. As I have not used Promises before, I'm struggling with how to deal with it in the best way.
What I have tried so far doesn't work as I try to combine synchronous and asynchronous programming:
var uid = ...;
"Some string".replace(/\#\{([\w]*?)\}/gmi, function(m, c) {
var r = "";
db.one("SELECT a FROM ... WHERE x = $1 AND y = $2", [c, uid])
.then(function(data) {
r = data.a;
});
return r;
});
r
is, unsurprisingly, an empty string. Is there a way to rewrite this block to "wait" for the values from the database?
What I try to do is, to replace placeholders in a message that is send to the user. So the above is part of a function called prepareMessage
and I send the message to the user using socket.io so it looks something like this:
io.to(socket.id).emit('message', { text: prepareMessage(msg) });