javascript - 如何将异步(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: {} }
不确定我在技术上缺少什么来解决结果。
一旦我有了承诺(包装器),是什么触发它解决?如果没有发生这种情况,可能的问题是什么?
感谢任何能提供帮助的人。
解决方案
最后你的 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 = '';
}
推荐阅读
- arrays - 使用不同的阈值替换多列中的值
- xml - 将java对象转换为soap头
- spring-boot - Amazon MQ 消费者无法获取数据
- excel - 从 ssrs 导出到 excel 时无法维护日期格式
- c++ - 返回不同类型的变量
- javascript - 如果全职则按钮颜色为蓝色 但如果兼职按钮颜色为红色
- android - Android:在地图片段上显示用户位置
- verilog - vvp时verilog中的无限循环
- javascript - 如何在内部将每个数组元素传递给javascript中“map”函数内部使用的回调函数
- digital-ocean - 我正在使用 python-digitalocean 在 DO 上创建液滴。我无法将 ssh 密钥附加到液滴