首页 > 解决方案 > 如何将异步(AJAX)函数的结果存储在变量中?

问题描述

这不是一个重复的问题。

这是一个请求帮助寻找技术结论,在 如何从异步调用返回响应中未解决?

如果 .then() 没有解决 Promise,我该如何追踪问题?似乎我在技术上错过了一些东西,而不是在概念上。

此函数从 URL 检索数据:

async function getINFO(source, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", source);
    xhr.responseType = "document";
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200){
            var text = xhr.responseXML.getElementsByTagName('pre')[0].innerHTML;
            console.log(text);
            callback(text);
    }
  }
  xhr.send();
}

外部定义的回调:

function asyn_return(input){
  console.log(input);
  return input;
}

数据在 AJAX 中完美返回。

我想datastore.info用数据填充属性成员 ()。

info是一个 URL 字符串。

这是代码中我使用 AJAX 数据检索功能的地方:

if (typeof(info) === 'string'){
// If I have a URL retrieve the data and add it to the datastore object.
    datastore.info = getINFO(info, asyn_return).then(data =>{
      console.log(data);
      return data;
    });
    //console.log(datastore.info);
} else {
    datastore.info = "";
}

console.log(datastore.info);

console.log(data)返回我期望的数据,但未datastore.info填充:

{item1: "data", item2:"data", info: {} }

不确定我在技术上缺少什么来解决结果。

一旦我有了承诺(包装器),是什么触发它解决?如果没有发生这种情况,可能的问题是什么?

感谢任何能提供帮助的人。

标签: javascriptajaxasynchronous

解决方案


最后你的 console.log 假设数据是以非同步方式来的,但它不是,因此它是未定义的,因为 ajax 数据还没有到达。

您需要将代码更改为异步代码,它可以通过 Promise 或 async/await 重写。

可以这样写:

function getINFO(source) {
  return new Promise(resolve => {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', source);
    xhr.responseType = 'document';
    xhr.onreadystatechange = function() {
      if (xhr.readyState === 4 && xhr.status === 200) {
        var text = xhr.responseXML.getElementsByTagName('pre')[0].innerHTML;
        console.log(text);
        resolve(text);
      }
    };
    xhr.send();
  });
}

if (typeof info === 'string') {
  // If I have a URL retrieve the data and add it to the datastore object.
  getINFO(info).then(data => {
    console.log(data);
    datastore.info = data;
    // continue your async code here
  });
  //console.log(datastore.info);
} else {
  datastore.info = '';
}

推荐阅读