【问题标题】:How to get PromiseValue in XMLHttpRequest. JSON如何在 XMLHttpRequest 中获取 PromiseValue。 JSON
【发布时间】: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


【解决方案1】:

sendRequest() 将执行异步。这意味着即使未加载数据,脚本也会继续。所以最后一行console.log(getData) 将在任何数据加载之前发生。

这就是 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));

另一种选择是使用异步和等待。但这不适用于旧版浏览器。

function async sendRequest(method, url, data = null) {
// your current xhr code
}

let getData = await sendRequest('GET', baseUrl + '/users');
console.log(getData);

【讨论】:

    【解决方案2】:

    我认为您必须返回 data 的值,如提到的 here 才能完成承诺

    sendRequest 返回的promise 被解析后,它会立即将一个新的promise 传递给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 
    })
    

    看看这个question

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-03
      • 2015-08-16
      • 2018-12-25
      • 2011-12-24
      • 1970-01-01
      • 2020-07-04
      • 2013-05-07
      • 1970-01-01
      相关资源
      最近更新 更多