用 pg-promise 中的数据替换文本

Replacing text with data from pg-promise

我想用 pg-promise 数据库中的值替换字符串中的一些文本。由于我之前没有使用过 Promises,所以我正在努力寻找如何以最好的方式处理它。

我尝试结合同步和异步编程时,到目前为止我尝试的方法不起作用:

var uid = ...;
"Some string".replace(/\#\{([\w]*?)\}/gmi, function(m, c) {
    var r = "";
    db.one("SELECT a FROM ... WHERE x =  AND y = ", [c, uid])
        .then(function(data) {
            r = data.a;
        });
    return r;
});
毫不奇怪,

r 是一个空字符串。对于数据库中的值,有没有办法将此块重写为 "wait"?


我尝试做的是替换发送给用户的消息中的占位符。所以上面是一个名为 prepareMessage 的函数的一部分,我使用 socket.io 将消息发送给用户所以它看起来像这样:

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

经过一些阅读和更多的思考,我想出了一个解决方案,如果其他人有类似的问题,我想补充一下。

(除了上面的问题,我还有一个更复杂的问题,即我的消息是一个字符串数组,并且要保持顺序。)

关键是使用 tasks 将所有查询作为一个包发送到数据库,并等待所有结果发送到 return。这导致了以下代码:

// Sample data
var messages = ["String 1 with no placeholder.",
"String 2, #{placeholder1}, String 2.2.",
"String 3 with some more #{placeholder2}."];

// Collect all matches in array
var matches = [];
messages.forEach(function(text, index) {
  const regex = /\#\{([\w]*?)\}/gmi;
  var m;
  do {
    matches.push(regex.exec(text))
  } while(m);
});

// Request data from the database
db.task(function(t) {
  return t.batch(matches.map(function(m) {
    return t.oneOrNone("SELECT ... FROM ... WHERE id = ", [m[1]])
  }));
})
.then(function(r) {
        // Replace all occurrences of placeholders
        r.forEach(function(p) {
          messages = messages.map(function(t) { return t.replace("#{"+p.id+"}", p.replacement); });
        });

        // Send message to user
        io.emit('text', messages)M
      })
.catch(function(e) {
        // ... error handling ...
      });