Call An Asynchronous Javascript Function Synchronously

前端 未结 8 1473
南方客
南方客 2020-11-22 17:37

First, this is a very specific case of doing it the wrong way on-purpose to retrofit an asynchronous call into a very synchronous codebase that is many thousands of lines lo

8条回答
  •  长发绾君心
    2020-11-22 17:45

    There is one nice workaround at http://taskjs.org/

    It uses generators which are new to javascript. So it's currently not implemented by most browsers. I tested it in firefox, and for me it is nice way to wrap asynchronous function.

    Here is example code from project GitHub

    var { Deferred } = task;
    
    spawn(function() {
        out.innerHTML = "reading...\n";
        try {
            var d = yield read("read.html");
            alert(d.responseText.length);
        } catch (e) {
            e.stack.split(/\n/).forEach(function(line) { console.log(line) });
            console.log("");
            out.innerHTML = "error: " + e;
        }
    
    });
    
    function read(url, method) {
        method = method || "GET";
        var xhr = new XMLHttpRequest();
        var deferred = new Deferred();
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4) {
                if (xhr.status >= 400) {
                    var e = new Error(xhr.statusText);
                    e.status = xhr.status;
                    deferred.reject(e);
                } else {
                    deferred.resolve({
                        responseText: xhr.responseText
                    });
                }
            }
        };
        xhr.open(method, url, true);
        xhr.send();
        return deferred.promise;
    }
    

提交回复
热议问题