javascript承诺不是异步

时间:2014-12-10 20:03:48

标签: javascript asynchronous xmlhttprequest promise

一旦http get请求设置为几个条件,我想只解析并返回promise。

var getPromise = function(url) {
    // Return a new promise.
    return new Promise(function(resolve, reject) {
        // Do the usual XHR stuff
        var req = new XMLHttpRequest();
        req.open('GET', url, true);

        req.onload = function() {
            // This is called even on 404 etc
            // so check the status
            if (req.status == 200) {
                console.log(req);
                if (req.response === '"1"') {
                    // Resolve the promise with the response text
                    resolve(req.response);
                    console.log(req.response);
                }
            } else {
                // Otherwise reject with the status text
                // which will hopefully be a meaningful error
                reject(Error(req.statusText));
                console.log(Error(req.statusText));
            }
        };

        // Handle network errors
        req.onerror = function() {
            reject(Error("Network Error"));
        };

        // Make the request
        req.send();
    });
}

window.promise = getPromise(url);
window.promise.then(function(response) {
    // Execute code after agent leg is connected
    console.log("Connected!!!!!");
}, function(error) {
    console.error("Failed!", error);
});

我遇到的问题是HTTP get请求只解析了1次并将promise设置为挂起状态。为了查看更改后的状态,我需要在控制台中再次运行此代码。 我的理解是设置req.open(,, true)会使这个异步。 我希望它只在req.response ='" 1"'

时设置promise对象

提前致谢

0 个答案:

没有答案