将json数据导出到fetch范围之外

问题描述 投票:0回答:1

我正在尝试创建一个从api获取数据的简单示例。

fetch("https://api.example.com/results")
        .then((response) => response.json())
        .then(function(data) {
            console.log(data)
});

现在,我的网页上有数据,但我想将数据“导出”到fetch之外,这样我就可以根据表单过滤数据了。有没有办法做到这一点?

javascript
1个回答
0
投票

正如zabusa所提到的,你可以创建一个执行过滤的函数,然后在fetch的.then链中调用该函数:

function filter(data) {
    console.log("Filtering based on " + JSON.stringify(data))
    // add the rest of your filtering code here
}

fetch("https://reqres.in/api/users/2")
    .then((response) => response.json())
    .then(function(data) {
        filter(data)
});

您可能还想考虑使用await,如下所示:

var response = await fetch("https://reqres.in/api/users/2")
var data = await response.json()
filter(data)

甚至:

filter(await (await fetch("https://reqres.in/api/users/2")).json())
© www.soinside.com 2019 - 2024. All rights reserved.