我目前正在开发一个基于 lunr.js 的 JavaScript 全文搜索客户端项目。
问题是,我正在努力构建然后保存索引,因为我有几个异步调用。
function buildIndex(rawIndex, root, indexPath = root + 'js/app/index.json') {
var path = path || require('path');
var fs = fs || require('fs'),
promesses = [],
ignore = ['node_modules'],
files = fs.readdirSync(root);
files.forEach(function (file) {
if (fs.statSync(path.join(root, file)).isDirectory() && ignore.indexOf(file) == -1) {
buildIndex(rawIndex, path.join(root, file), indexPath);
}
else if (file.substr(-5) === '.html' && file != 'example.html') {
var promesse = JSDOM.fromFile(path.join(root, file)).then(dom => {
var $ = require('../lib/_jquery')(dom.window);
populate();
console.log(file + " indexé");
function populate() {
$('h1, h2, h3, h4, h5, h6').each(function () {
var title = $(this);
var link = path.join(root, file).replace('..\\', '') + "#" + title.prop('id');
var body = title.nextUntil('h1, h2, h3, h4, h5, h6');
rawIndex.add({
id: link,
title: title.text().latinise(),
body: body.text().latinise()
});
});
};
});
promesses.push(promesse);
}
});
Promise.all(promesses)
.then(function () {
fs.writeFileSync(indexPath, "var data = " + JSON.stringify(rawIndex), 'utf8');
})
.catch(function (err) {
console.log("Failed:", err);
});
};
提前致谢。
使用 forEach 不是正确的选择,因为人们想要返回一个 Promise。因此,使用 .map 然后在 if/else 语句中返回 Promises 是更明智的做法。最后,必须调用 Promises.all(promises) 使 .then(...) 按预期可用。
我的最终功能:
function buildIndex(rawIndex, root, indexPath = root + 'js/app/index.json') {
var path = path || require('path');
var fs = fs || require('fs'),
promises = [],
ignore = ['node_modules'],
files = fs.readdirSync(root);
var promises = files.map(function (file) {
if (fs.statSync(path.join(root, file)).isDirectory() && ignore.indexOf(file) == -1) {
return buildIndex(rawIndex, path.join(root, file), indexPath);
}
else if (file.substr(-5) === '.html' && file != 'example.html') {
return JSDOM.fromFile(path.join(root, file)).then(dom => {
var $ = require('jquery')(dom.window);
populate();
console.log(file + " indexé");
function populate() {
$('h1, h2, h3, h4, h5, h6').each(function () {
var title = $(this);
var link = path.join(root, file).replace('..\\', '') + "#" + title.prop('id');
var body = title.nextUntil('h1, h2, h3, h4, h5, h6');
rawIndex.add({
id: link,
title: title.text().latinise(),
body: body.text().latinise()
});
});
};
})
}
})
return Promise.all(promises).then(function () {
fs.writeFileSync(indexPath, "var data = " + JSON.stringify(rawIndex), 'utf8');
});
};
感谢@Bergi 的回答和那些提供帮助的人。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句