0

I just wrote a simple and small API to define the gender of a person. It works via a get-request to a page which gives me back a JSON object.

This is the code of my module:

'use strict';
const https = require('https');

exports.getGender = function (name) {
  return new Promise((resolve) => {
    //send request to api
    https.get(`https://api.genderize.io?name=${name}`, (resp) => {
      var data = '';
      //replace data
      resp.on('data', (chunk) => {
        data += chunk;
      });
      //define information on end of query
      resp.on('end', () => {
        var info = JSON.parse(data);
        //check accuracy of gender
        if (info.probability >= 0.8) {
          //check gender
          if (info.gender == 'male') {
            resolve('Sehr geehrter Herr');
          } else if (info.gender == 'female') {
            resolve('Sehr geehrte Frau');
          }
        } else {
          resolve('Sehr geehrte/r Frau / Herr');
        }
      });
    });
  });
};

And this is the call I do in the main file:

//get gender of person
async function getG(name) {
  const data = await genderApi.getGender(name);
  return data;
}

getG('Tim');

But the output is just Promise { <pending> }, If I replace the return data with a console.log(data) it just works fine and it shows me the output in the console but I really need it to return the value cause later on I use this function in a text back to the user

Kartikey
  • 4,516
  • 4
  • 15
  • 40
silliton
  • 3
  • 1
  • 3

1 Answers1

0

getG function is also async so you must use with await keyword or .then callback

const val = await getG('Tim');
// or
getG('Tim').then((val) => {
 console.log(val)
})
Kartikey
  • 4,516
  • 4
  • 15
  • 40
Faruk
  • 399
  • 2
  • 8
  • the first solution does not work because await just works inside a async function and the other one does also just return Promise – silliton Sep 20 '21 at 23:23
  • Yes async function works inside async function but you can use *self-invoking function* like `(async () => {const val = await getG('Tim')})()`. – Faruk Sep 20 '21 at 23:38
  • well I tried it but its also not working for me :( – silliton Sep 20 '21 at 23:40