从API(对象)创建承诺

时间:2017-07-08 12:30:25

标签: javascript node.js promise

我使用的API是owapi.net/api/v3/u/Calvin-1337/stats(名称将更改)。让我们说我想要tier,那就是JSON.us.stats.competitive.overall_stats.tier我可以解析它并让它好起来。但现在我想创造一个承诺。让我们为overall_stats做出... us.stats.competitive.overall_stats,我现在只需要那里的值。我不能做类似的事情:

const core = require("myNodePackage");

core.getCompOverallStats("Calvin-1337").then(data > {
    console.log(data.tier) // grandmaster
    // etc through to
    console.log(data.prestige) // 5
});

这完全错了,但我想到的是:

const fetch = require("node-fetch"); // used to get json data

getCompOverallStats = (playerName) => {
    return new Promise((resolve, reject) => {

        // only want this for us.stats.competitive.overall_stats

        fetch("https://owapi.net/api/v3/u/Calvin-1337/stats")
            .then(function(res) => {
                return res.json();
            }).then(function(json) {
                //console.log(json.us.stats.competitive.overall_stats.tier) => grandmaster
            });

1 个答案:

答案 0 :(得分:1)

getCompOverallStats = (playerName) =>
  // grab the player stats
  fetch(`https://owapi.net/api/v3/u/${playerName}/stats`)
    // parse json
    .then(res => res.json())
    // pull out the one object you want
    .then(data => data.us.stats.competitive.overall_stats);

这应该足够了。

您现在应该可以致电

getCompOverallStats('some-pl4y3r').then(overall => console.log(overall.tier));