我正在编写一个新的 Promise,它有许多不同的条件,调用与其状态相关的 reject()
或 resolve()
,而且我知道 Promise 状态将在第一次调用 reject()
时设置 | resolve()
。
我的问题是:
是否有任何 native (内置)方法来获取 promise 状态?
以下是演示代码:
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 to check if this promise is rejected or resolved yet?
})
.catch(function (err) {
reject(err);
})
})
};
最佳答案
您无法直接检查 Promise 的状态。他们不是这样工作的。您可以对它们使用 .then()
或 .catch()
并通过回调来获取通知。
或者,在您的具体情况下,您可以更改代码的结构方式以删除 anti-pattern创建不必要的外部 promise 并将逻辑切换为 if/else if/else。
这是清理后的代码:
exports.addStatement = function (db, description, data) {
return validator.validateStatement(description, data)
.then(function (data) {
//......
if(cnd1) {
// make res be the resolved value of the promise
return res;
} else if(cnd2) {
// make promise become rejected with err as the reason
throw err;
} else {
// decide what else to do here
}
})
})
};
如果您无法使 if/else 为您工作,上述结构应该仍然有效,因为 return
和 throw
都会终止 的执行code>.then()
处理程序。因此,在它们之后继续的唯一代码是尚未为当前 Promise 设置已解决/拒绝值的代码,因此您不必查看 Promise 的状态即可知道这一点。如果代码通过了 return
和 throw
并且仍在执行,那么它们都没有被执行,并且当前 Promise 的已解析/已拒绝值仍未设置。
关于javascript - 在编写新的 Promise 时如何检查这个 Promise 状态? js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38823059/