Q诺链错误后存在诺言链

我有一个node.js脚本,打开一个Azure容器,跨越多个不同国家的页面截图,同时将它们传输到Azure容器。 我遇到的问题是如果我在stream媒体过程中遇到错误,它完成该给定ID的剩余屏幕截图,然后退出承诺链。

所以,如果我在Id 211006遇到错误,它会完成所有截图,然后退出stream。 它不会继续。

我很新的承诺如何工作,他们是如何捕捉错误,但我的理解是,如果211006确实遇到错误,脚本将完成承诺链,然后在运行.fin之前显示我的任何错误 -事实并非如此。

任何人都可以帮忙吗?

 AzureService.createContainer() .then(function () { return ScreenshotService.getAllCountriesOfId('308572'); }) .then(function () { return ScreenshotService.getAllCountriesOfId('211006'); }) .then(function () { return ScreenshotService.getAllCountriesOfId('131408'); }) .then(function () { return ScreenshotService.getAllCountriesOfId('131409'); }) .then(function () { return ScreenshotService.getAllCountriesOfId('789927'); }) .then(function () { return ScreenshotService.getAllCountriesOfId('211007'); }) .then(function () { return ScreenshotService.getAllCountriesOfId('833116'); }) // Upload Log file into Azure storage .fin(function () { AzureService.init({ container: config.azure.storage.msft.CONTAINER.LOG, account: config.azure.storage.msft.ACCOUNT, key: config.azure.storage.msft.ACCESS_KEY, file: config.file.log, isLogFile: true }); log.info('Utility: Uploading log file [ %s ] to Azure storage container [ %s ]', AzureService.file, AzureService.container); return AzureService.uploadLocalFileToStorage() .then(function () { return util.deleteFile({fileName: AzureService.file, isLogFile: true}); }) .fail(function (err) { log.info(err); }) .done(); }) .fail(function (err) { log.info(err); }) .done(); 

任何时候,允许一连串的承诺,一个错误被允许回到链中。 这将承诺状态设置为拒绝,并将调用任何后续的.then()处理程序中的下一个error handling程序,而不是履行的处理程序。

如果你想链条继续,那么你需要捕捉错误。 捕获错误将导致承诺基础设施将其视为“已处理”,承诺状态将再次被履行,并将继续执行已完成的处理程序。

承诺错误类似于例外。 如果不处理,则会中止处理直到第一个exception处理程序。 如果使用exception处理程序处理它们,则处理将在该exception处理程序之后正常继续。

在你的具体情况下,如果你想继续查询,你将需要在这些types的行中处理错误:

 return ScreenshotService.getAllCountriesOfId('308572'); 

你可以这样做:

 return ScreenshotService.getAllCountriesOfId('308572').then(null, function(err) { console.log(err); // error is now handled and processing will continue }); 

既然你有很多重复的代码,你可能应该把你的代码改成遍历国家ID数组的东西,而不是一遍又一遍地复制代码行。


这里有一个使用.reduce()来链接循环中的所有承诺,并摆脱这么多重复的代码,并处理个别国家的错误,使链继续:

 var countryIds = ['308572', '211006', '131408', '131409', '789927', '211007', '833116']; countryIds.reduce(function(p, item) { return p.then(function() { return ScreenshotService.getAllCountriesOfId(item).then(null, function(err) { console.log(err); }); }); }, AzureService.createContainer()) // Upload Log file into Azure storage .fin(function () { ... rest of your code continued here