javascript - 我不明白如何在 js 中返回变量。XMLHttpRequest()
问题描述
const xhr = new XMLHttpRequest()
xhr.open('GET', requestURL)
xhr.onload = () => {
const data = (JSON.parse(xhr.response))
}
xhr.send()
是否甚至可以返回“常量数据”。无论如何我都需要使用那个json
解决方案
通过承诺返回值。将代码包装在 Promise 中并返回 Promise。
function httpCall(){
return new Promise((resolve, reject){
const xhr = new XMLHttpRequest()
xhr.open('GET', requestURL)
xhr.onload = () => {
if(xhr.status == 200) {
const data = (JSON.parse(xhr.response));
resolve(data);
} else {
reject("Failure to fetch data.");
}
}
xhr.send();
});
}
并通过 async / await 调用调用该函数。
async function makeHttpCall(){
const data = await httpCall();
console.log(data);
}
推荐阅读
- python - 比较包装函数是否是装饰器的实例
- python - 如何删除熊猫中属于同一组的某些 k 条目,例如余额类?
- python - 如何确定嵌套列表结构是否与另一个相同,但元素交换为新的
- postgresql - 错误:类型时间戳的无效输入语法:“20-MAR-17 08.30.41.453267 AM”
- loops - 如何创建动态 while 循环?
- php - 获取值列表,然后获取具有该值的所有帖子标题
- java - 如何在 BasicInterpreter 的 GETSTATIC 和 PUTSTATIC 命令中唯一标识静态变量
- python - 如何使用 Pandas 保留我的组中使用的列名
- python - 如何通过 tesseract OCR 读取黑色背景图像上的黑色文本?
- javascript - 如何打印 HTML 地理位置?