javascript - How to check this promise state, when programming a new promise? js -
i programming new promise, has many different conditions call reject()
or resolve()
related state, know promise state set first call reject()
| resolve()
. question is: there native (build-in) way promise state? following demonstrative-code:
exports.addstatement = function (db, description, data) { return new promise(function (resolve, reject) { validator.validatestatement(description, data) .then(function (data) { //...... if(cnd1) resolve(res); if(cnd2) reject(err); //...... //how check if promise rejected or resolved yet? }) .catch(function (err) { reject(err); }) }) };
you cannot directly examine state of promise. that's not how work. can use .then()
or .catch()
on them callback notified.
or, in specific case, can change way code structured remove anti-pattern of creating unnecessary outer promise , switching logic if/else if/else.
here's cleaned code:
exports.addstatement = function (db, description, data) { return validator.validatestatement(description, data) .then(function (data) { //...... if(cnd1) { // make res resolved value of promise return res; } else if(cnd2) { // make promise become rejected err reason throw err; } else { // decide else here } }) }) };
if couldn't make if/else work you, above structure should still work because both return
, throw
terminate execution of .then()
handler. so, code continues after them code has not yet set resolved/rejected value current promise don't have @ state of promise know that. if code gets past return
, throw
, still executing, neither of executed , resolved/rejected value of current promise still unset.
Comments
Post a Comment