In the code below, I am calling Pouch.sync()
, to which I chain deleteLocal()
. Pouch.sync()
executes localDb.sync()
, which does not return a promise, but I can attach a .on()
event handler to handle errors.
I've tried playing around with $q.when and $q.reject, but I can't seem to prevent deleteLocal()
from firing if the sync fails, and onError()
never executes (either as an error callback or in the catch statement).
// Controller
function _onSyncClick() {
return Pouch.sync()
.then(deleteLocal, onError); // I do not want deleteLocal() to execute if Pouch.sync() fails
.catch(onError);
}
// Pouch service
function sync() {
return
localDb.sync(remoteDb)
.on('error', function (err) {
return $q.reject('Sync error.');
});
}
答案 0 :(得分:0)
.synch()
uses a callback API, you can use $q.when
and $q.reject
to promisify it.
return localDB.sync(remoteDB).on('complete', function () {
return $q.when("done!");
}).on('error', function (err) {
return $q.reject(err);
});
Also, when chaining promises, you need to make sure you either throw
an error or return a rejected promise, otherwise you will trigger the resolve
/success
handler.
so either .on('error', errorHandler)
didn't ran as you though it would
or Pouch.sync()
didn't invoke your function.
答案 1 :(得分:0)
首先,您then()
不应使用deleteLocal
致电onError
。
接下来,基于Angular文档:如果通过promise错误回调“捕获”错误,并且想要将错误转发到从当前promise中派生的promise,则必须“重新抛出”错误通过返回通过$q.reject
因此,您将回调事件视为承诺,也许这就是为什么不抛弃拒绝。
我认为正确的方法是使用sync()
构造函数从$q
Promisify回调事件。
// Controller
function _onSyncClick() {
return Pouch.sync().then(deleteLocal).catch(onError);
}
// Pouch Service, method sync
function sync() {
return $q(function (resolve, reject) {
localDb.sync(remoteDb, {
// options
}).on('complete', function (info) {
resolve(info);
}).on('error', function (err) {
reject(err);
});
});
}
提一下,$q.when
包装一个可能是值的对象或(第三方)然后能够承诺进入$ q承诺,不要将它用作解析,用它来包装PouchDB承诺。