node.js - Replacing text with data from pg-promise -


i replace text in string values database using pg-promise. have not used promises before, i'm struggling how deal in best way.

what have tried far doesn't work try combine synchronous , asynchronous programming:

var uid = ...; "some string".replace(/\#\{([\w]*?)\}/gmi, function(m, c) {     var r = "";     db.one("select ... x = $1 , y = $2", [c, uid])         .then(function(data) {             r = data.a;         });     return r; }); 

r is, unsurprisingly, empty string. there way rewrite block "wait" values database?


what try is, replace placeholders in message send user. above part of function called preparemessage , send message user using socket.io looks this:

io.to(socket.id).emit('message', { text: preparemessage(msg) });

after reading , more thinking, came solution i'd add if else has similar problem.

(in addition question above, had additional complication message array of strings , order kept.)

the key use tasks send queries db 1 package , wait results return. led following code:

// sample data var messages = ["string 1 no placeholder.", "string 2, #{placeholder1}, string 2.2.", "string 3 more #{placeholder2}."];  // collect matches in array var matches = []; messages.foreach(function(text, index) {   const regex = /\#\{([\w]*?)\}/gmi;   var m;   {     matches.push(regex.exec(text))   } while(m); });  // request data database db.task(function(t) {   return t.batch(matches.map(function(m) {     return t.oneornone("select ... ... id = $1", [m[1]])   })); }) .then(function(r) {         // replace occurrences of placeholders         r.foreach(function(p) {           messages = messages.map(function(t) { return t.replace("#{"+p.id+"}", p.replacement); });         });          // send message user         io.emit('text', messages)m       }) .catch(function(e) {         // ... error handling ...       }); 

Comments

Popular posts from this blog

python - How to insert QWidgets in the middle of a Layout? -

python - serve multiple gunicorn django instances under nginx ubuntu -

module - Prestashop displayPaymentReturn hook url -