Return value from callback function

后端 未结 2 500
孤独总比滥情好
孤独总比滥情好 2020-12-09 23:34

I have few functions, which calls another (integrated functions in browser), something like this:

function getItems () {
    var xhr = new XMLHttpRequest();
         


        
2条回答
  •  一个人的身影
    2020-12-10 00:02

    This seems be an async request. I don't think you will be able to return data from this function.

    Instead, you can take a callback function as an argument to this function and call that callback when you have the response back.

    Example:

    function getItems (callback) {
        var xhr = new XMLHttpRequest();
        xhr.open("GET", "http://another.server.tld/", true);
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
                callback(xhr.responseText);
            }
        };
        xhr.send();
    }
    

提交回复
热议问题