承诺的复杂sorting – 嵌套

经过大量的search,我还没有能够确认这个问题的正确方法。 下面的代码按预期的方式运行,但我有一个严重的感觉,我没有以正确的方式来处理这个问题,而且我正在设法解决问题。

以下代码由主app.js文件启动,并通过一个位置开始加载XML文件并将其加工到mongoDB

exports.processProfiles = function(path) { var deferrer = q.defer(); q(dataService.deleteProfiles()) // simple mongodb call to empty the Profiles collection .then(function(deleteResult) { return loadFilenames(path); // method to load all filenames in the given path using fs }) .then(function(filenames) { // now we have all the file names lets load and save filenames.forEach(function(filename) { // Here is where i think the problem is! // kick off another promise chain for the dynamically sized array of files to process q(loadFileContent(path, filename)) // first we load the data in the file .then(function(inboundFile) { // then parse XML structure to my new shiny JSON structure // and ask Mongo to store it for me return dataService.createProfile(processProfileXML(filename, inboundFile)); }) .done(function(result) { console.log(result); }) }); }) .catch(function(err) { deferrer.reject('Unable to Process Profile records : ' + err); }) .done(function() { deferrer.resolve('Profile Processing Completed'); }); return deferrer.promise; } 

虽然这些代码起作用,但这些都是我主要关心的问题,但经过几个小时的Google阅读之后,无法自行解决。

1)这是封锁吗? 读到控制台很难理解,如果这是asynchronous运行,因为我想它 – 我认为这只是build议,如果我做一些根本的错误将是伟大的

2)嵌套承诺是一个坏主意,我应该把它连接到外部的承诺 – 我已经尝试,但不能得到任何东西来编译或运行。

我在很长一段时间内没有使用过Q,但我认为你需要做的是让它知道你将要交还一系列需要全部满足的承诺,然后继续前进。

另外,当你在一段代码中等待多个承诺,而不是进一步嵌套时,一旦满意,抛出承诺的“集合”。

 q(dataService.deleteProfiles()) // simple mongodb call to empty the Profiles collection .then(function (deleteResult) { return loadFilenames(path); // method to load all filenames in the given path using fs }) .then(function (filenames) { return q.all( filenames.map(function (filename) { return q(loadFileContent(path, filename)) { /* Do stuff with your filenames */ }); }) ); .then(function (resultsOfLoadFileContentsPromises) { console.log('I did stuff with all the things'); ) .catch(function(err) {});