【问题标题】:Firebase - Can I set() existing JSON into Real-Time Database?Firebase - 我可以将现有的 JSON 设置()到实时数据库中吗?
【发布时间】:2022-11-30 03:05:42
【问题描述】:

我正在制作一个应该显示实时足球数据的应用程序。对于后端,我从 API 获取数据,并希望将其放入 Firebase 的实时数据库中,以便在应用程序中获取实时数据。来自 API 的数据已经以 JSON 格式出现,那么有什么方法可以利用它吗?

实时数据库的顶层应该是固定时间间隔的日期,在每个日期下,我想嵌套来自 API 的 JSON 数据。

下面是我目前尝试使用 set() 方法插入到实时数据库中的方式,但在当前状态下没有任何反应。

import { initializeApp } from "firebase/app";
import { getDatabase, ref, set } from "firebase/database";
import { getDates } from './dates.js';
import { getDataApi, getCurrentSeason } from './api_manager.js';
import { idList } from '../data/data.js';

const firebaseConfig = {
...
};

const app = initializeApp(firebaseConfig);
const db = getDatabase();

function update() {
    var startDate = new Date();
    var season = getCurrentSeason().then(val => val);
    var datesArr = getDates(startDate, 7);

    datesArr.forEach(date => {
        idList.forEach(id => {
            const reference = ref(db, `${date}/${id}`);
            var data = getDataApi(date, id, season);
            set(reference, data);
        });
    });
}

update();

如果有任何兴趣,这些是我从 API 获取数据的方法:

import fetch from 'node-fetch';

const options = {
  method: 'GET',
  headers: {
    ...
  }
};

export async function getDataApi(date, leagueId, season) {
    const url = `https://api-football-v1.p.rapidapi.com/v3/fixtures?date=${date}&league=${leagueId}&season=${season}`;

    try {
        let response = await fetch(url, options);
        let json = await response.json();
        return json['response'];
    } catch (error) {
        console.log("Error: " + error);
    }
}

export async function getCurrentSeason() {
    const url = 'https://api-football-v1.p.rapidapi.com/v3/leagues?id=39&current=true';
    try {
        let response = await fetch(url, options);
        let json = await response.json();
        return json['response'][0]['seasons'][0]['year'];
    } catch (error) {
        console.log("Error: " + error);
    }

}

【问题讨论】:

  • “什么都没发生”真的很难帮助。您是否已在本地调试问题?如果你在你分享的代码的每一行都设置了一个断点,在调试器中运行代码,然后检查每一行的每个变量的值,这是第一的行不符合您的预期?

标签: javascript json firebase firebase-realtime-database


【解决方案1】:

您的 getCurrentSeasongetDataApi 函数被标记为 async,但您在调用它们时并未使用 await。即使是您的then() 调用也无法正常工作,因为所有需要该值的代码都必须是里面then()回调。

一个简单的方法:

async function update() {
    var startDate = new Date();
    var season = await getCurrentSeason(); // ?
    var datesArr = getDates(startDate, 7);

    datesArr.forEach(date => {
        idList.forEach(id => {
            const reference = ref(db, `${date}/${id}`);
            var data = await getDataApi(date, id, season); // ?
            set(reference, data);
        });
    });
}

请注意,此代码在您的update(); 调用返回后仍将继续运行,因此请检查您的进程是否过早终止。

一般来说,我建议阅读 asynchronous operations in JavaScript,因为你会不断遇到它。

【讨论】:

    猜你喜欢
    • 2017-11-30
    • 2019-02-23
    • 2019-12-27
    • 1970-01-01
    • 1970-01-01
    • 2021-07-23
    • 1970-01-01
    • 2023-01-17
    • 1970-01-01
    相关资源
    最近更新 更多