2017-07-08 1 views
0

私が使用しているAPIはowapi.net/api/v3/u/Calvin-1337/statsです(名前は変更されます)。私がtierを望んでいたら、それはJSON.us.stats.competitive.overall_stats.tierとなり、それを解析して大丈夫になるとしましょう。しかし、今私は約束を作りたいと思っています。 overall_statsのためにそれを作ろう... us.stats.competitive.overall_statsと私は瞬間だけそこから値が欲しいです。API(オブジェクト)からプロミスを作成

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 
      }); 
+0

を呼び出すことができるはずです。 – OmG

+1

return fetch.then(d => d.json());十分です... –

+0

['Promise'コンストラクタの反パターンを避けてください](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-それ)! – Bergi

答えて

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

を私のような何かを行うことができるようにwan't。

あなたは今、 "Q" モジュールを使用して

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

+0

これで私はエラーが発生しています。 'core.getCompOverallStats(" Calvin-1337 ")。then(data => { ^ TypeError:未定義のプロパティ 'then'を読み取ることができません –

+0

これを無視して、返すことを忘れました。 –

関連する問題