Back

Callback on function not working

  • 0
  • Web
Vârli
23 May, 2024, 18:11

I am working on a Node.js web function to retrieve data from an API and add it to my Appwrite database. However, when I tried debugging if the data is being retrieved, the callbacks from the http function do not seem to work as I get an empty response when I try to execute the function

TypeScript
import { Client, Databases } from "node-appwrite";
import http from 'http';

export default async ({ req, res, log, error }) => {
    const client = new Client();
    const databases = new Databases(client);

    client
        .setEndpoint(process.env.APPWRITE_BACKEND_ENDPOINT)
        .setProject(process.env.APPWRITE_PROJECT_ID)

    if(req.method == "POST") {
        let data = {};
        const options = {
            hostname: 'http://api.syntesio.ro',
            port: 80,
            path: '/SyntesioServices/api/v1/core/product/list',
            method: 'GET',
            headers: {
                'Authorization': process.env.CHARA_API_AUTH_KEY
            }
        }
        const request = http.request(options, (response) => {
            response.setEncoding('utf-8');

            response.on('data', (chunk) => {
                return res.json(JSON.parse(chunk));
            });

            response.on('end', () => log(`Response data string end`));
        })

        request.on('error', (error) => error(error.message));
        request.end();

        return res.json(data);
    }
};
TL;DR
Developers faced an issue with callbacks not working in their Node.js function while trying to retrieve data and encountered an empty response. They sought to use async/await with `http.request` function but struggled to find a solution. To resolve the problem, they need to wait for the response before proceeding with the logic instead of returning an empty response immediately.
Evdog
23 May, 2024, 18:26

Might be empty because it's moving on before it's actually returned, might want to change your logic to wait for the response before proceeding

Vârli
23 May, 2024, 18:27

how should i do it?

Vârli
23 May, 2024, 18:27

cause i wanna try to use async / await on the http.request function but I didn't find any solutions

Vârli
23 May, 2024, 18:33

nevermind, our lord and saviour chatgpt solved it

Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more