HTTP Request: making request from a function

I think I’m missing something here…I built a script for daily weather forecast from Dark Sky.

This set of code from the main body of script works fine:

let place = await Location.current()
let keys = devKey()
let site = “https://api.darksky.net/forecast/
let url = site + keys + “/” + place.latitude + “,” + place.longitude
let req = new Request(url)
let json = await req.loadJSON()

For sake of better modularity and more importantly for some simple mocking of the API call, I tried to move this to a function, like below, but get a syntax error. Any ideas on what might be wrong?

SyntaxError: Unexpected identifier ‘req’. Expected ‘;’ after variable declaration

let place = await Location.current()
let json = getWeather(place)

function getWeather(place) {
let keys = devKey()
let site = “https://api/darksy.net/forecast/
let url = site + keys + “/” + place.latitude + “,” + place.longitude
let req = new Request(url)
let json = await req.loadJSON()
return json
}

Does your “let url” statement actually occur on two lines or is just formatted that way here?

If it’s actually on two lines then add a semi colon at the end of the statement.

JavaScript auto semi colon insertion is probably causing issues.

No that wasn’t it. You need to change your function declaration to:

async function getWeather(place) {

If you have an “await” inside a function you need to declare the function with “async”. That error message you received is weird and confusing. However adding async should fix the issue.

When you mark a function with async it means the function will return a promise resolved with the value of the return statement. In case the value of the json object.

2 Likes

@scottfwalter Thanks for the extra quick response…adding async to the function definition and a await to the getWeather() call fixed the issue.

Thanks a bunch for the help.

– John

1 Like