Javascript 如何在XMLHttpRequest中获取PromiseValue。JSON
如何获取位于PromiseValue上的数组,而不是获取PromiseValue上的数组 当我使用Javascript 如何在XMLHttpRequest中获取PromiseValue。JSON,javascript,json,promise,xmlhttprequest,Javascript,Json,Promise,Xmlhttprequest,如何获取位于PromiseValue上的数组,而不是获取PromiseValue上的数组 当我使用时,然后(data=>console.log(data))我在控制台日志中获取数组。 但是,我需要获取一个数组来将其放置在html页面上,因此我将代码更改为。然后(data=>data),并开始获取Promise{} const baseUrl = 'http://localhost:3000'; function sendRequest(method, url, data = null) {
时,然后(data=>console.log(data))
我在控制台日志中获取数组。
但是,我需要获取一个数组来将其放置在html页面上,因此我将代码更改为。然后(data=>data)
,并开始获取Promise{}
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
返回的承诺后,它将立即向getData
传递一个新的承诺
.then(data => {
return data;
})
.catch (err => {
console.log(err);
})
看起来像这样
function sendRequest(s){
return new Promise((resolve, reject) => {
resolve(s) ;
});
}
let getData = sendRequest("test")
.then(value => {
return value;
})
getData.then(value => {
console.log( value);
//access value
})
看看这个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));
另一种选择是使用async和wait。但这在较旧的浏览器中不起作用
function async sendRequest(method, url, data = null) {
// your current xhr code
}
let getData = await sendRequest('GET', baseUrl + '/users');
console.log(getData);
这回答了你的问题吗?