简体   繁体   中英

Waiting for an asynchronous function in clean JavaScript

I'm currently working with XMLHttpRequest() and as a result I have an asynchronous function. I want to be able to run some code after the XMLHttpRequest is finished. My code so far:

var method = function() {
    this.func = function(param) {
        _xmlrequestfunc(param, function(r) {
            // return something
        }
    }
}

What I want to be able to do with this function is the following:

method.func('POST').Then(
    // Do something when method.func() is finished
)

I would like to do this in clean JavaScript... Is this possible and if so can anyone explain how it is done? Thanks in advance!

Just pass a function as callback...

this.func = function(param, callback) {
    _xmlrequestfunc(param, function(r) {
        if(callback) callback();
        // return something
    }
}

.....
this.func({yourprams}, responseFunc);

function responseFunc() {
    //I am being called after the successful completion of XMLRequest.
}

If you want to have it in clean JS, you can return this self-made promise from your func() :

var promise = {
    resolve: function (data) {
        this.callback(data);
    },
    Then: function (callback) {
        this.callback = callback;
    }
};

_xmlrequestfunc(param, function(r) {
    promise.resolve(42);
});

return promise;

This way you can use return value as you wanted:

method.func('POST').Then(function (theAnswer) {});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM