代码说明:
如果互联网可用,它将根据不同的方法同步来自不同表的未同步数据。但是,我想知道如何为这些不同的函数添加 promise 。我在启动所有函数时使用的逻辑但同时,我想在 function1 成功的基础上启动 function2 并重复相同的过程,任何人都可以告诉我该怎么做。
function syncApp () {
$log.log('offlineOnlineSync got called');
Contact.syncApp().then(function (resp) {
$log.log('Contact sync got called', resp);
WorkerGroup.syncApp().then(function (resp) {
$log.log('WorkerGroup sync got called', resp);
Category.syncApp().then(function (resp) {
$log.log('Category sync got called', resp);
Vehicle.syncApp().then(function (resp) {
$log.log('Vehicle sync got called', resp);
Daybook.syncApp().then(function (resp) {
$log.log('Daybook sync got called', resp);
}, CommonService.errorHandler);
}, CommonService.errorHandler);
}, CommonService.errorHandler);
}, CommonService.errorHandler);
}, CommonService.errorHandler);
}
在第一个方法中,发生的过程是这样的,但在完成上述过程之前,会调用第二个方法。
prom = DB.update('contacts', servResp, 'id', key)
.then(function () {
if (servResp.type === 'Worker') {
WorkerGroup.checkGroupForTempIds(key, servResp.id)
.then(function (resp) {
$log.log('Response in contact service', resp);
}, function (err) {
$log.log('err: ', err);
});
} // fix me // not needed
}, function (err) {
$log.log('err: ', err);
});
$log.log('serverresponseid', servResp.id);
$log.log('key', key);
var daybook_updatequery = 'UPDATE daybook SET contact_id = ? WHERE contact_id = ?';
$cordovaSQLite.execute(Database.db, daybook_updatequery, [servResp.id, key])
.then(function (resp) {
$log.log('response', resp);
defer.resolve('success');
}, function (err) {
q.reject(err);
$log.log(err);
});
proms.push(prom);
});
$q.all(proms).then(function () {
defer.resolve('success');
});
最佳答案
您可以链接 promise ,因此您只需要一个错误处理程序:
function syncApp () {
$log.log('offlineOnlineSync got called');
return Contact.syncApp().then(function (resp) {
$log.log('Contact sync got called', resp);
return WorkerGroup.syncApp();
}).then(function (resp) {
$log.log('WorkerGroup sync got called', resp);
return Category.syncApp();
}).then(function (resp) {
$log.log('Category sync got called', resp);
return Vehicle.syncApp();
}).then(function (resp) {
$log.log('Vehicle sync got called', resp);
return Daybook.syncApp();
}).then(function (resp) {
$log.log('Daybook sync got called', resp);
}).catch(function(err) {
CommonService.errorHandler(err);
});
}
关于javascript - 如何保证 AngularJS 中的多种功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45461826/