如何向打字稿函数添加可选回调?

2024-02-09

我可以进行 javascript ajax 调用,如下所示:

$.getJSON( "http://localhost:62178/document?filename=c:/test/dave.docx", function( data ) {
    console.log("read = " + data);
}).done(function(e) {
    console.log( "second success" );
})
    .fail(function(e, f, g) {
        console.log( "error" );
    })
    .always(function(e) {
        console.log( "complete" );
    });

我如何声明并编写一个具有等效功能的打字稿类?换句话说,如果我的类有一个 getJSON() 方法,我该如何编写它才能拥有 main 函数和可选的命名函数?

谢谢-戴夫


在评论中被要求提供示例后,我决定将其作为单独的答案发布,以便更容易区分它们。

当然还有很多需要改进的地方。例如,可以做的一件事是允许将处理程序附加到承诺,即使在延迟已解决之后(它们将立即触发)。这样也可以处理同步请求。

当然,您可以添加其他回调等。同样,这只是一个小例子! :)

enum Status {
    SUCCESSFUL, FAILED
}

interface Callback { (): void; }

class Deferred {
    public promise : Promise = new Promise();

    public resolve( status : Status = Status.SUCCESSFUL ) {
        if( status === Status.SUCCESSFUL ) {
            this.executeCallback( this.promise.cbSuccess );
        } else {
            this.executeCallback( this.promise.cbFail );
        }
    }

    private executeCallback( callback : Callback ) {
        if( callback ) {
            callback.call( null );
        }
    }
}

class Promise {
    public cbSuccess : Callback;
    public cbFail : Callback;

    public success( callback : Callback ) : Promise {
        this.cbSuccess = callback;
        return this;
    }

    public fail( callback : Callback ) : Promise {
        this.cbFail = callback;
        return this;
    }
}

// =======
// Example
// =======

function getJson( url : string ) : Promise {
    var deferred = new Deferred();

    // simulate some asynchronous operation
    setTimeout( function someAsynchRequest() {
        var result = Math.random() < 0.5
            ? Status.SUCCESSFUL : Status.FAILED;

        console.log( "Asynchronous operation finished [result: "
            + Status[result] + "]!" );

        // resolve our deferred with the result we got
        deferred.resolve( result );
    }, 3000 );

    // return only the promise because the caller actually
    // doesn't need to know about the deferred itself
    // (e.g. the caller shouldn't be able to resolve it)
    return deferred.promise;
}

getJson( "no one cares" )
    .success( function () {
        console.log( "Callback came back with success!" );
    } ).fail( function () {
        console.log( "Callback came back with failure :(" );
    } );
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何向打字稿函数添加可选回调? 的相关文章

随机推荐