一旦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对象提前致谢