【发布时间】:2017-08-11 17:48:11
【问题描述】:
我对 Node.js 中递归异步请求的行为有疑问。
下面的函数旨在从 MongoDB 返回搜索结果。如果初始搜索结果为空,我将文本拆分为单个单词,然后尝试为每个单词递归 fetchResult(...),将 res 对象作为参数传递。
function fetchResult(text, res){
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect(mongoURL + "/search", function (err, db) {
if(err) throw err;
db.collection('results', function(err, collection) {
// search for match that "begins with" text
collection.findOne({'text':new RegExp('^' + text, 'i')}, function(err, items){
var result = (items == null || items.result == null) ? "" : items;
if (result){
res.send(result);
}
else {
// no result, so fire off individual word queries - if any spaces found
if (text.indexOf(' ') > -1){
// split string into array
var textArray = text.split(" ");
// recursively process individual words
for (index = 0; index < textArray.length; index++) {
// ***** RACE CONDITION HERE? *****
fetchResult(textArray[index], res);
}
}
else {
// just return empty result
res.send(result);
}
}
});
});
});
}
我怀疑这可能会导致一些竞争条件,因为对 res 的引用是异步扇出的,当我运行代码并观察到以下错误时证实了这一点:
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)
所以我的问题是:如何实现按顺序执行单个字符串查询的所需递归行为,仅在我们找到第一个结果时返回(或在搜索返回时在流程结束时返回完全没有结果)?
【问题讨论】:
-
研究应许
标签: javascript node.js asynchronous recursion