android - JavaScript Exception Is Lost In Promise Chain -
i new javascript promises , trying implement them phonegap code on android device. want log exceptions , looks exceptions swallowed somewhere. see sample code below. exception thrown due call non-existent function "thiswillfail" not show anywhere. commented out irrelevant code , added code force addrecord promise called. code checks if record exists and, if not, return addrecord promise error is. not using 3rd party libraries. doing wrong?
edit: if add promise in chain "dosomethingwithrecord", promise called when expectation skip catch.
function testpromiseexceptionhandling() { var record = null; var checkforrecord = function () { return new promise(function (resolve, reject) { //getdata( // function (data) { var data = ""; if (data != "") { //record = new record(data); record = "existed"; resolve(); } else return addrecord(); // }, // function (err) { // reject(new error("an error occurred retrieving data, msg=" + err.message)); // }); }); }; var addrecord = function () { return new promise(function (resolve, reject) { thiswillfail(); //add record var success = true; record = "new"; if (success) resolve(); else reject(new error("add record failed")); }); }; var dosomthingwithrecord = function () { return new promise(function (resolve, reject) { alert(record); resolve(); }); }; try { checkforrecord() .then(dosomthingwithrecord()) .catch(function (err) { alert(err.message);}) .then(function () { alert("done"); }); } catch (err) { alert(err.message); }}
you can't return promise constructor, when do:
else return addrecord();
nothing wait addrecord, instead, want resolve addrecord wait before resolving promise:
else resolve(addrecord());
however, if code can return addrecord()
instead of using promise constructor anyway. promise constructor (new promise) useful converting non-promise apis promises , aren't supposed used promisified apis. use then
s instead.
Comments
Post a Comment