Javascript 按顺序连续处理项目列表,完成后返回ok(异步->;同步)
我对承诺和异步过程的概念非常感兴趣。我已经订购了一个列表,并希望对每个项调用一个函数,等待第一个项的第一个过程完成,然后继续第二个、第三个,依此类推。只有在处理完每一个项目后,我才想继续主要的过程Javascript 按顺序连续处理项目列表,完成后返回ok(异步->;同步),javascript,q,Javascript,Q,我对承诺和异步过程的概念非常感兴趣。我已经订购了一个列表,并希望对每个项调用一个函数,等待第一个项的第一个过程完成,然后继续第二个、第三个,依此类推。只有在处理完每一个项目后,我才想继续主要的过程 module.exports = { hooks: { "init": function() { var options = this.options.pluginsConfig['regexplace'] || {}; options.substitutes =
module.exports =
{
hooks: {
"init": function() {
var options = this.options.pluginsConfig['regexplace'] || {};
options.substitutes = options.substitutes || {};
// collects text replacement queries from plugin configuration
options.substitutes.forEach(function (option) {
patterns.push({re: new RegExp(option.pattern, option.flags || ''),
sub: option.substitute,
decode: option.decode || false,
store: option.store || null,
unreset: option.unreset || false});
});
this.config.book.options.variables = this.config.book.options.variables || {};
processPages(this);
},
"page": function(page) {
var that = this;
// process all normal sections in page
page.sections.filter(function(section) {
return section.type == 'normal';
})
.map(function(section) {
collectStore(section, page, that, true);
});
return page;
}
}
};
下面是使其与主进程配合良好的代码。所以返回Q.all(承诺)的结果是首先处理所有承诺,然后继续主过程。但问题是,项目(导航键)是异步处理的,而我需要它们同步:
function processPages(that) {
var navs = [];
Object.keys(that.navigation).map(function(key) {
navs.push({key: key, order: parseInt(that.navigation[key].index)});
});
var promises = navs.sort(function(a, b) {
return a.order - b.order;
})
.map(function(item) {
return that.parsePage(item.key).then(function(page) {
return page.sections.filter(function(section) {
return section.type == 'normal';
})
.map(function(section) {
collectStore(section, page, that);
});
});
});
return Q.all(promises);
}
以下是我修改项目以同步和正确顺序处理时的代码,但现在主进程将不同步:
function processPages(that) {
var navs = [];
Object.keys(that.navigation).map(function(key) {
navs.push({key: key, order: parseInt(that.navigation[key].index)});
});
var promises = navs.sort(function(a, b) {
return a.order - b.order;
})
.reduce(function(previous, item) {
return previous.then(function () {
return that.parsePage(item.key).then(function(page) {
return page.sections.filter(function(section) {
return section.type == 'normal';
})
.map(function(section) {
collectStore(section, page, that);
});
});
});
}, Q());
return Q.all(promises);
}
有人知道这里发生了什么,以及在这种情况下如何正确使用承诺吗
其他信息
processPages是从init hook调用的。若并没有使用promise(Q.all),那个么页面钩子可能会在init钩子被完全处理之前触发,这也是我不能允许的。这就是我所说的“主要过程”
代码是GitBook插件代码的一部分。请查看来自的可运行示例(来自Chrome的开发控制台),尤其是“链接”示例 根据您对“…我已订购了一个列表,希望调用一个包含每个项目的函数”,等待第一个项目的第一个过程完成,然后继续第二个、第三个,依此类推。只有在处理完每个项目后,我才希望继续执行主过程” 从算法的角度来看,您应该将多个承诺“链接”在一起:
- 为每个项目创建承诺。当一个项目完成时,调用resolve(),以便执行(链中的下一个项目)
- 将“主流程”作为链中的最后一项
希望这有帮助!:-) 解决方案非常简单,只需更改:
processPages(this);
到
在init hook上。但现在主进程将不同步,除了您认为它意味着什么,并没有描述任何内容。如果你希望事情按顺序处理,那么不要使用
承诺
在过程循环中处理它们。。。我们都应该看看这篇文章。谢谢,这给了我一些测试的想法。我已经怀念过去没有太大承诺的日子了。
return processPages(this);