如何将异步(AJAX)函数的结果存储在变量中?

时间:2019-06-26 07:44:06

标签: javascript ajax asynchronous

这不是重复的问题。

这是一项寻求技术结论的帮助,但在 How do I return the response from an asynchronous call?

如果.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: {} }

不确定要从技术上解决这个问题的原因。

一旦有了诺言(包装器),是什么触发了诺言的解决? 而当这种情况没有发生时,可能的问题是什么?

感谢任何可以提供帮助的人。

1 个答案:

答案 0 :(得分:0)

最后,您的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 = '';
}