0

我想用数据库中的值替换字符串中的一些文本pg-promise。由于我以前没有使用过Promise,因此我正在努力解决如何以最佳方式处理它。

到目前为止,我尝试将同步和异步编程结合起来并不起作用:

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不出所料,它是一个空字符串。有没有办法重写这个块来“等待”数据库中的值?


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

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

4

1 回答 1

0

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

(除了上面的问题,我的消息是一个字符串数组并且要保留顺序。)

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

// 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 = $1", [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 ...
      });
于 2016-11-03T09:05:45.960 回答