javascript - 使用 async/await 查找 cors 请求的值?

标签 javascript jquery asynchronous async-await

我正在尝试执行 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/

相关文章:

JavaScript 土耳其手机号码验证

javascript - 主干、js 和 node.js 渲染和路由

javascript - 鼠标离开视口(viewport)时如何使 JQuery .hover() 工作?

C# async/await - 限制调用异步方法/锁定的次数

python - 如何在 Python 中异步接收来自多个 WebSocket 的数据?

python - 如何在 Twisted 中调试 Protocol.dataReceived

javascript - Angular JS/Bootstrap 应用程序路由在 Internet Explorer 中不起作用

javascript - Canvas js : how to remove a datapoint dynamically but without creating a "hole" in chart?

jquery,任何相对改变顶部位置的短版本

jquery - 如果 JSON 对象中有空格,则会出现语法错误。如何逃离太空?