[英]Create a Promise from an API (object)
The API I'm using is owapi.net/api/v3/u/Calvin-1337/stats
(the name will change). 我使用的API是
owapi.net/api/v3/u/Calvin-1337/stats
(名称会更改)。 Let's say I wanted the tier
, that'd be JSON.us.stats.competitive.overall_stats.tier
and I can parse that and get it okay. 假设我想要
tier
,那就是JSON.us.stats.competitive.overall_stats.tier
,我可以解析它并使其正常。 But now I want to create a promise. 但是现在我要创造一个诺言。 Let's make it for the
overall_stats
so... us.stats.competitive.overall_stats
and I only want values from there for the moment. 让我们为
overall_stats
它,以便... us.stats.competitive.overall_stats
,我us.stats.competitive.overall_stats
只想从那里获取值。 I wan't to be able to do something like: 我将无法执行以下操作:
const core = require("myNodePackage");
core.getCompOverallStats("Calvin-1337").then(data > {
console.log(data.tier) // grandmaster
// etc through to
console.log(data.prestige) // 5
});
This is totally wrong but what I had thought about: 这是完全错误的,但我曾想过:
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
});
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);
That should be enough. 那应该足够了。
You should now be able to call 您现在应该可以打电话了
getCompOverallStats('some-pl4y3r').then(overall => console.log(overall.tier));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.