0

I'm learning Javascript and Node.js.

I am trying to return the body of the response by using node-fetch but I received an undefined output.

Is there any way that I can get the body returned?

const express = require('express')
const router = express.Router()
const fetch = require('node-fetch');

router.get('/', (req, res) =>{

    let zipcode = req.query.zipcode;

    let temp = getGeoCode(zipcode);
    
    console.log(temp); 

**//here returns promise<pending>**

    temp.then(function(result){

        console.log(result); 

**//here returns undefined**
    })

 async function getGeoCode(zipcode){

   await fetch(`https://public.opendatasoft.com/api/records/1.0/search/?dataset=us-zip-code-latitude-and-longitude&q=${zipcode}&facet=state&facet=timezone&facet=dst&refine.state=MA`)
    .then(
        res =>res.json()
        )
    .then(json => {
        res.send(`The lon and lat in your zipcode "${zipcode}" - ${json.records[0].fields.city}, ${json.records[0].fields.state} is ${json.records[0].fields.longitude}, ${json.records[0].fields.latitude}.`) 

**//Here works well!!!**
        
    })
    .catch(error =>{
        console.log(error)
    })

 }

})
Frances
  • 23
  • 3
  • "here returns undefined" — Because you don't have a return statement! – Quentin Feb 18 '21 at 11:09
  • `await`ing `fetch` is pointless because you don't do anything in the function afterwards (and that makes making `async` pointless since you don't don't have any `await`s inside the function). `async` and `await` are *great* but you need to replace `then()` and `catch()` for them to have any useful effect. – Quentin Feb 18 '21 at 11:11
  • Your code would be easier to read if you used consistent indenting. There are plenty of code formatting tools out there, many of which will integrate with popular editors. – Quentin Feb 18 '21 at 11:12
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – coagmano Feb 18 '21 at 11:12

1 Answers1

0

It's as simple as that when you stop messing with your head with the .then() Promise-style, and you use only the async/await style :

router.get('/', async (req, res) => {
    let zipcode = req.query.zipcode;
    const response = await fetch(`....`);
    const result = await response.json();
    console.log(result);
    res.send(`The lon and lat.....`)
})
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63