Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在XMLHttpRequest中获取PromiseValue。JSON_Javascript_Json_Promise_Xmlhttprequest - Fatal编程技术网

Javascript 如何在XMLHttpRequest中获取PromiseValue。JSON

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) {

如何获取位于PromiseValue上的数组,而不是获取PromiseValue上的数组 当我使用
时,然后(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);

这回答了你的问题吗?