简体   繁体   English

如何在 XMLHttpRequest 中获取 PromiseValue。 JSON

[英]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 
})

Have a look at this question看看这个问题

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.

相关问题 如何使用 Promise { 获取 PromiseValue<pending> 火力基地? - How to get PromiseValue with Promise {<pending>} Firebase? 未捕获的语法错误:JSON.parse 处的 JSON 输入意外结束(<anonymous> ) 在 XMLHttpRequest。<anonymous> ((指数):32)</anonymous></anonymous> - Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) at XMLHttpRequest.<anonymous> ((index):32) 如何在tensorflow.js中获取tf.toPixels()的返回值的PromiseValue - How to get the PromiseValue of the return value of tf.toPixels() in tensorflowjs XMLHttpRequest。 WSDL请求。 readyState == 4,但状态== 0 - XMLHttpRequest. WSDL request. readyState == 4, but status == 0 如何获取JSON以成功解析XMLHttpRequest字符串? - How to get JSON to successfully parse a XMLHttpRequest string? 如何将 JSON 数据添加到对 XMLHttpRequest 的 GET 请求? - How to add JSON data to GET request to XMLHttpRequest? 如何从 JSON XMLHttpRequest 获取值? - How to get values from JSON XMLHttpRequest? 从退回的承诺中获得PromiseValue - Get PromiseValue out of Returned Promise XMLHttpRequest的。 不以UTF-8发送数据。 任务是不可能的? - XMLHttpRequest. Send data NOT in UTF-8. Is mission imposible? Firefox扩展:使用XMLHttpRequest的多个请求。 是否使用异步? - Firefox Extension: multiple requests with XMLHttpRequest. Use Asynchronous or not?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM