如何重用API中提取的数据?

时间:2017-03-14 12:04:49

标签: javascript json

我从返回JSON对象的API中获取数据:

fetch("api.php")
.then(function(response) {
    console.log("Status: " + response.status);
    if (response.ok) {
        return response.json(); 
    } else {    
        throw Error(response.status);
    }
}).then(function(json) {
    json.forEach(function(item) {

        // 'datas' contains the items extracted from the JSON response
        datas.add(item);


    });
}).catch(function(err) {
    console.log(error);
});

如果我想使用jinqJs查询数据,我可以稍微更改代码:

}).then(function(json) {
    var result = new jinqJs()
        .from(json)
        .where('start_date = 2017-03-10')
        .select();

    result.forEach(function(item) {

        datas.add(item);

    });
}).catch(function(err) {

它的效果非常好。

我的问题是:由于只提取一次API,我实际上下载了所有需要的数据,我怎样才能在“{1}}之外”查询它?我的意思是:我已经拥有一次调用API的所有数据,我可以使用jinqJs轻松地对数据进行查询为什么每次需要查询时都应该调用API? forEach fetch添加了所有项目后,是否可以查询datas

例如,在forEach之外(注意forEach而不是.from(datas))我可以这样做:

.from(json)

并获得相同的var result = new jinqJs() .from(datas) .where('start_date = 2017-03-10') .select();

当我正在尝试构建一个移动应用程序时,这会很方便,因为我会将上面的代码绑定到特定的按钮并相应地查询数据,我会在第一次启动应用程序时连接到互联网而不是每次需要查询时。

1 个答案:

答案 0 :(得分:1)

将“JSON”承诺分配给变量

var something = fetch("api.php")
.then(function(response) {
    console.log("Status: " + response.status);
    if (response.ok) {
        return response.json(); 
    } else {    
        throw Error(response.status);
    }
});

现在您可以根据需要多次使用something

something
.then(json => console.log(json))
.catch ...

something.then(json => new jinqJs()
    .from(json)
    .where('start_date = 2017-03-10')
    .select()
    .forEach(function(item) {
        datas.add(item);
    });
).catch ....
相关问题