如何获取位于PromiseValue
上的数组,而不是获取Promise {<pending>}
当我使用.then(data => console.log(data))
时,我正在控制台日志中获取数组。但是,我需要获取一个数组以将其放置在html页面上,因此我将代码更改为.then(data => data)
并开始获取Promise {<pending>}
const baseUrl = 'http://localhost:3000';
function sendRequest(method, url, data = null) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.responseType = 'json';
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = () => {
if (xhr.status >= 400) {
reject(xhr.response);
} else {
resolve(xhr.response);
}
}
xhr.onerror = () => {
reject(xhr.response);
}
xhr.send(JSON.stringify(data));
});
}
let getData = sendRequest('GET', baseUrl + '/users')
.then(data => data)
.catch(err => console.log(err));
console.log(getData);
提前感谢。
sendRequest()
将执行异步。这意味着即使未加载数据,脚本仍会继续。因此,最后一行console.log(getData)
将在加载任何数据之前发生。
这是诺言可用于:
sendRequest('GET', baseUrl + '/users') .then(function(data){ // The response can only be processed in the .then part. // You can, however, call other functions with the fetched data console.log(data); }) .catch(err => console.log(err));
另一个选择是使用异步并等待。但这在较旧的浏览器中不起作用。
function async sendRequest(method, url, data = null) {
// your current xhr code
}
let getData = await sendRequest('GET', baseUrl + '/users');
console.log(getData);
我认为您必须返回data
的here值才能完成承诺