CodexBloom - Programming Q&A Platform

How to implement guide with asynchronous function not returning expected result in node.js

πŸ‘€ Views: 63 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-14
node.js async-await promises javascript

I'm working with a question with an asynchronous function in my Node.js application that doesn't seem to be returning the expected result. I have a function that fetches data from an external API and processes it, but instead of returning the processed data, it returns `undefined`. Here’s a simplified version of the function: ```javascript const fetch = require('node-fetch'); async function fetchData(url) { const response = await fetch(url); const data = await response.json(); // Processing the data return data.results; // Assuming data.results is what I need } function getProcessedData() { const result = fetchData('https://api.example.com/data'); console.log(result); // Expected to log the processed data } getProcessedData(); ``` When I run the `getProcessedData` function, instead of logging the fetched results, I see `Promise { <pending> }`. I understand that `fetchData` is asynchronous and returns a promise, but I thought using `await` would handle that. I tried adding `await` in front of the `fetchData` call, but that resulted in a syntax behavior because `await` can only be used inside an `async` function. To fix this, I tried changing my `getProcessedData` function to be asynchronous: ```javascript async function getProcessedData() { const result = await fetchData('https://api.example.com/data'); console.log(result); } ``` Now, when I call `getProcessedData()`, it returns a promise, but I still don't see the expected logged output in the console. I've also confirmed that the API is returning data correctly by testing the URL directly in my browser. What am I missing here? How can I properly wait for the asynchronous function to resolve and log the result?