javascript - 从 API(对象)创建 Promise

标签 javascript node.js promise

我使用的 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/

相关文章:

javascript - Node.Js promise 重定向不起作用

javascript - Express next() 中间件不会触发 .catch() block 中的下一个中间件

javascript - 如何为 Promise.all 参数映射字符串数组?

php - 无法从 PHP json_encode 转换或访问 JSON 对象

javascript 关闭按钮不起作用

php - 多个输入字段上的 Jquery 日期选择器

node.js - docker-compose POSTGRES & SEQUELIZE 的数据库连接错误

javascript - 将函数添加到具有两个输入字段的 .keyup()

node.js - 通过 Heroku 安全地使用 Google 服务帐户

javascript - 如何在:run after tests finish execution之后触发cypress