承诺的两种实现之间的差异

Difference between 2 implementations of promises

本文关键字:之间 实现 两种 承诺      更新时间:2023-09-26

我在我的网站上使用承诺(仍在学习),我想知道这之间是否有区别:

    return promise
            .then(ctxTransport.getTransportById(idTran, transport))
            .then(checkLocking)
            .fail(somethingWrong);

:

    return promise
        .then(function () { return ctxTransport.getTransportById(idTran, transport); })
        .then(function () { return checkLocking(); })
        .fail(somethingWrong);

在第一次实现时,有时会出现错误

var getTransportById = function (transportId, transportObservable, forceRemote) {
    // Input: transportId: the id of the transport to retrieve
    // Input: forceRemote: boolean to force the fetch from server
    // Output: transportObservable: an observable filled with the transport
    ...
    return manager.executeQuery(query)
        .then(querySucceeded)
        .fail(queryFailed);
    function querySucceeded(data) {
        transportObservable(data.results[0]);
    }
};
function checkLocking() {
     var now = new Date();
     transport().lockedById(5);
     transport().lockedTime(now);
     return ctxTransport.saveChanges(SILENTSAVE);
 }
 function somethingWrong(error) {
     var msg = 'Error retreiving data. ' + error.message;
     logError(msg, error);
     throw error;
 }

谢谢。

在promise链中传递函数时,您应该传递不带参数或()的函数名,或者像第二种情况一样,传递匿名函数。这是因为Q将使用先前承诺解析的结果/返回值为您调用它。

因此,.then(ctxTransport.getTransportById(idTran, transport))在语义上是不正确的,因为您传递的不是函数,而是ctxTransport.getTransportById的返回值。