我有一个 node.js 脚本,它打开一个 Azure 容器,截取多个不同国家/地区的页面屏幕截图,同时将其流式传输到 Azure 容器。我遇到的问题是,如果我在流处理过程中遇到错误,它会完成给定 id 的剩余屏幕截图,然后退出 promise 链。
因此,如果我在 ID 211006
处遇到错误,它会完成所有屏幕截图的拍摄,然后退出流。它不会继续下去。
我对 Promise 的工作原理以及它们如何捕获错误非常陌生,但我的理解是,如果 211006
确实遇到错误,脚本将完成 Promise 链,然后在运行 .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();
最佳答案
只要允许错误返回链中, promise 链就会停止。这会将 Promise 状态设置为拒绝,并将调用任何后续 .then()
处理程序中的下一个错误处理程序,而不是已完成的处理程序。
如果您希望链继续,那么您需要捕获错误。捕获错误将导致 Promise 基础设施将其视为“已处理”,并且 Promise 状态将再次实现,并将继续执行已实现的处理程序。
Promise 错误类似于异常。如果未处理它们,它们将中止处理,直到第一个异常处理程序为止。如果使用异常处理程序处理它们,则处理将在该异常处理程序之后正常继续。
在您的具体情况下,如果您希望继续进行链接,则需要处理每种类型的行中的错误:
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()
将所有 promise 链接到循环中的方法,并消除大量重复代码并处理个别国家/地区错误,以便链继续:
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
关于javascript - Q promise 链在错误后存在 promise 链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33441209/