【问题标题】:Node request data from API, push data to array. Then run another request using that new array节点从 API 请求数据,将数据推送到数组。然后使用该新数组运行另一个请求
【发布时间】:2018-03-09 18:43:29
【问题描述】:
var UfcAPI = require('ufc-api');

var ufc = new UfcAPI({
    version: '3'
});

const fighterId = [];

function getFighterId() {
    ufc.fighters(function(err, res) {
        for (let i = 0; i < res.body.length; i++) {
            fighterId.push(res.body[i].id);
        }
        // console.log(fighterId);
    })
};

function allFighters() {
    for (let j = 0; j < fighterId.length; j++) {
        request("http://ufc-data-api.ufc.com/api/v3/us/fighters/" + fighterId[j] + ".json", function(error, response, body) {
            if (!error && response.statusCode === 200) {
                console.log(JSON.parse(body));
            }
        })
    }
};

第一个函数 getFighterId() 将通过 json 查找 UFC 名册上的所有战士。我捕获每个战斗机的所有 Id 并将其推送到 fighterId 数组。然后我想做一个循环用他们的 id 查询战士,以获取每个战士的更详细信息。

我知道我需要将数组完全填满,然后运行我的第二个函数。我找到了有关 Promise 和 Async 的信息,但对如何实现它感到非常困惑。

谢谢

【问题讨论】:

标签: javascript node.js api loops request


【解决方案1】:
var UfcAPI = require('ufc-api');

var ufc = new UfcAPI({
    version: '3'
});

function allFighters(fighterIds) {
    fighterIds.forEach(fighterId => {
        request("http://ufc-data-api.ufc.com/api/v3/us/fighters/" + fighterId + ".json", function(error, response, body) {
            if (!error && response.statusCode === 200) {
                console.log(JSON.parse(body));
            }
        })
    });
};

function getFighterId(){
    return new Promise((resolve,reject)=>{

        ufc.fighters((err,res)=>{
            if(err) reject(err);
            else resolve(res.body)
        })

    })

}

getFighterId()
.then((ufcData)=>ufcData.map((u)=>u.id))
.then((data)=>allFighters(data))
.catch((err)=>console.log(err));

请试试我用 Promises 实现的这个。它可以通过更多方式实现。如果对您有帮助,请告诉我。

【讨论】:

    猜你喜欢
    • 2021-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-17
    • 2018-07-11
    • 2017-10-18
    • 1970-01-01
    相关资源
    最近更新 更多