在编程新的promise时,如何检查此promise状态?js

How to check this promise state, when programming a new promise? js

本文关键字:promise 检查 状态 js 何检查 编程      更新时间:2023-09-26

我正在编程一个新的promise,它有许多不同的条件来调用与其状态相关的reject()resolve(),而且我知道promise状态将在第一次调用reject()|resolve()时设置。我的问题是:是否有任何本地(内置(方式可以获得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(),并通过回调获得通知。

或者,在您的特定情况下,您可能会更改代码的结构方式,以消除创建不必要的外部承诺并将逻辑切换为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为您工作,那么上面的结构应该仍然可以工作,因为returnthrow都会终止.then()处理程序的执行。因此,唯一在它们之后继续的代码是尚未为当前promise设置已解析/已拒绝值的代码,因此您不必查看promise的状态即可知道这一点。如果代码超过returnthrow并且仍在执行,那么这两个代码都没有执行,并且当前promise的已解析/已拒绝值仍然未设置。