-2

I created a basic function that's calling another function that should return a result and then I want to log it from the main function but when I do it it's just not waiting and log (undefined) and not waiting for the result to arrive.

const returnBool = async () => {
  const googleData = await getData();
  console.log(googleData);
};


const getData = () => {
  googleTrends
    .interestOverTime({ keyword: `Test` })
    .then(function (results) {
      console.log(results);
      return results;
    })
    .catch(function (err) {
      console.error('Oh no there was an error', err);
    });
};
LearningReact
  • 83
  • 1
  • 6

1 Answers1

3

Your getData function doesn't return a Promise, so (a)waiting for it doesn't do much. googleData is therefore still undefined the moment you try to log it to console.

Try , for example, wrapping your getData code inside a Promise, like this :

const getData = () => {
  return new Promise((resolve, reject) => {
  
    googleTrends
    .interestOverTime({ keyword: `Test` })
    .then(function (results) {
      return resolve(results);
    })
    .catch(function (err) {
      return reject(err);
    });

  });
}

Also I would suggest adding a try ... catch block to the first async function, like this

const returnBool = async () => {
  try {
  
    const googleData = await getData();
    console.log(googleData);

  } catch (ex) {
  
  }
};

Actually, depending on what you are actually trying to do, you could save some lines there and get rid of the additional function like this :

const returnBool = async () => {
  try {
  
    const googleData = await googleTrends.interestOverTime({ keyword: 'Test' });
    return googleData ? true : false;

  } catch (ex) {
    /* error handling */
    return false
  }
}

And if I may, let me suggest one more thing. returnBool is not really a good name for a function. Try something more descriptive, like

const keywordHasData = async (keyword) => {
   // ... await googleTrends.interestOverTime({ keyword });
}
turbopasi
  • 3,327
  • 2
  • 16
  • 43