javascript - react 等待服务器响应

标签 javascript node.js reactjs

我想编写一个从 API 请求一些信息的应用程序。只要此信息不可用,我就不想继续申请的其余部分。我已经尝试过这个:

function suggestion(callback) {
    xhr.open('GET', 'http://localhost:3001/');
    xhr.onload = function() {
        var a = JSON.parse(xhr.responseText);
        console.log(a);
        callback(a);
    };
    xhr.send();
}

var sugg = suggestion(function(lista) {
    var s = [];
    lista.forEach(element => {
        s.push(element.event);
    });  
    console.log(s);

    return s; 
});

为什么 sugg 返回未定义?

最佳答案

As long as this informations isn't available I don't want to continue with the rest of the application

这不是你使用 Web 技术来做到这一点的方式(如果你使用 React,即使它是 React 原生的,你也会使用 Web 技术)。相反,您可以让应用程序在异步操作未完成时显示适当的“正在加载”或“挂起”状态,然后在操作完成时更新该状态。

Why sugg is returning undefined?

sugg未定义,因为suggestion 没有返回值。调用从不返回某些内容的函数的结果始终是未定义。事实上你的callback有一个return并不重要,没有任何东西使用callback()suggestion中返回的内容(即使确实如此,它也会在稍后执行,而不是在分配sugg时执行)。

因此,将这两条信息放在一起,我们得到:

function suggestion(callback){
    // (You probably need something declaring `xhr` and assigning
    // `new XMLHttpRequest()` to it here)
    xhr.open('GET', 'http://localhost:3001/');
    xhr.onload = function() {
        var a = JSON.parse(xhr.responseText);
        console.log(a);
        callback(a);
    };
    xhr.send();
}

showPendingState();      // ***
suggestion(function(lista){
    var s = [];
    lista.forEach(element => {
        s.push(element.event);
    });  
    console.log(s);
    showRealStateUsing(s); // ***
});

但是,我建议使用 promise 而不是原始回调,并处理错误情况。如果我们要使用 Promise,让我们使用现代的 fetch 而不是旧的 XHR:

function suggestion() {
    return fetch('http://localhost:3001/')
        .then(response => {
            if (!response.ok) {
                throw new Error("HTTP status " + response.status);
            }
            return response.json();
        });
}

showPendingState();
suggestion()
    .then(showRealStateUsing) // `showRealStateUsing` receives the suggestion as an argument
    .catch(showErrorState);   // `showErrorState` receives the error as an argument

如果您的目标环境支持 async functions (和/或转译),我们可以让事情变得更简单:

async function suggestion() {
    const response = await fetch('http://localhost:3001/');
    if (!response.ok) {
        throw new Error("HTTP status " + response.status);
    }
    return response.json();
}

// (in an `async` function)
showPendingState();
try {
    showRealStateUsing(await suggestion());
} catch (error) {
    showErrorState(error);
}

关于javascript - react 等待服务器响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53186430/

相关文章:

javascript - 如何在 iFrame 上显示图像?

javascript - NodeJS MVC 模型验证

javascript - 我的错误处理程序如何优先于早期的中间件

Node.js + mocha + webdriverjs : Failed tests kill suite

javascript - JSX 将其绑定(bind)到映射中的函数

javascript - 创建拖放卡时无法读取未定义的属性 'map'

javascript - Amcharts V4 如何在不重新加载整个图表的情况下更改数据?

javascript - 多行 HTML 选项标签的解决方法是什么?

reactjs - 从 componentDidMount() 调用 Typescript Apollo 查询

javascript - 使用 Rest api react redux 异步任务