[英]How to get PromiseValue in XMLHttpRequest. JSON
How to get array that is located on PromiseValue
instead of getting Promise {<pending>}
While I'm using .then(data => console.log(data))
I'm getting array in console log.如何获取位于PromiseValue
上的数组而不是获取Promise {<pending>}
当我使用.then(data => console.log(data))
时,我在控制台日志中获取数组。 However, I need to get an array to place it on the html page so I changet code to .then(data => data)
and started to get Promise {<pending>}
但是,我需要获取一个数组以将其放置在 html 页面上,因此我将代码更改为 .then .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);
Thanks in advance.提前致谢。
I think you will have to return the value of data
as mentioned here to complete the promise我认为您必须返回此处提到的data
值才能完成 promise
When promise returned by sendRequest
is resolved, it will immediately pass a new promise to getData
.当sendRequest
返回的 promise 被解析后,它会立即将一个新的 promise 传递给getData
。
.then(data => {
return data;
})
.catch (err => {
console.log(err);
})
looks something like this看起来像这样
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()
will execute async. sendRequest()
将执行异步。 This means that the script continues, even though the data is not loaded.这意味着即使未加载数据,脚本也会继续。 So the last line console.log(getData)
will already happen before any of the data is loaded.所以最后一行console.log(getData)
将在任何数据加载之前发生。
This is what promises can be used for:这就是 Promise 可用于:
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));
Another option would be to use async and await.另一种选择是使用异步和等待。 But this does not work in older browsers.但这在旧浏览器中不起作用。
function async sendRequest(method, url, data = null) {
// your current xhr code
}
let getData = await sendRequest('GET', baseUrl + '/users');
console.log(getData);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.