我使用的 API 是 owapi.net/api/v3/u/Calvin-1337/stats
(名称将会更改)。假设我想要 tier
,即 JSON.us.stats.competitive.overall_stats.tier
,我可以解析它并得到它。但现在我想创造一个 promise 。让我们将其用于 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
});
最佳答案
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));
关于javascript - 从 API(对象)创建 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44986251/