我正在尝试执行 CORS
请求,然后使用 async/await 从中获取值(value)(顺便说一句,我正在使用 jquery)。
我相信函数 createCORSRequest
和 executeCORSRequest 都可以正常工作,所以实现并不重要。 getDailyGames
函数使用 await 接收从 executeCORSRequest
创建的 promise ,然后返回该 promise 。
我的问题是在 $(document)
.ready 函数中实际使用了 promise(这基本上是 jquery 中的主要函数)。
在注释掉的行中,“.then”方法用于 getDailyGames
的结果以打印出函数的结果(这很好用)。
但是,我想将此 promise 的值存储在“结果”变量中并对其进行操作,但我无法从 promise 中获取它。
我如何正确地返回这个 promise ,以便我可以将解析后的值存储在一个变量中并用它做一些事情?
或者另一种提问方式:为什么 getDailyGames
中的“result”变量会得到一个 promise?不应该使用 await 和 promise 直接给你解决的值(value)吗?
$(document).ready(function() {
//getDailyGames(20190313).then(result => console.log(result));
let result = getDailyGames(20190313);
//DO STUFF WITH RESULT
});
async function getDailyGames(date){
const url = 'https://api.jjjacobson.com/dailygames?season=2018-2019-
regular&date=' + date;
let result = await executeCORSRequest(url);
return result;
}
function executeCORSRequest(url){
return new Promise(function(resolve, reject) {
const xhr = createCORSRequest('GET', url);
if (!xhr) {
throw new Error('CORS not supported');
}
xhr.onload = function() {
resolve(xhr.responseText);
};
xhr.onerror = function() {
console.log('There was an error!');
reject('ERROR');
};
xhr.send();
});
}
function createCORSRequest(method, url) {
let xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
xhr.open(method, url, true);
}
else if (typeof XDomainRequest != "undefined") {
// Otherwise, check if XDomainRequest.
// XDomainRequest only exists in IE, and is IE's way of making CORS requests.
xhr = new XDomainRequest();
xhr.open(method, url);
}
else {
// Otherwise, CORS is not supported by the browser.
xhr = null;
}
return xhr;
}
最佳答案
您应该将 document.ready 函数更改为:
$(document).ready(function() {
let result;
getDailyGames(20190313).then(res => {
result = res;
//DO STUFF WITH RESULT
});
});
Await
仅在函数本身为异步时才起作用。你也可以这样做
$(document).ready(async function() {
let result = await getDailyGames(20190313);
//DO STUFF WITH RESULT
});
关于javascript - 使用 async/await 查找 cors 请求的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55155316/