【发布时间】:2020-06-01 03:07:33
【问题描述】:
如何获取位于 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);
提前致谢。
【问题讨论】:
标签: javascript json promise xmlhttprequest