0

I have a script currently that needed to fetch data:

fetch("https://data.weather.gov.hk/weatherAPI/opendata/weather.php?dataType=flw&lang=en")
.then(r => r.json())
.then(result => console.log(result))

If I had to continue the script, I can use these methods:

Method 1:

function stuff(){
   ...
   .then(result => function(){ <code> })
}

Method 2:

function stuff(){
   ...
   .then(result => fetchcont(result))
}
function fetchcont(r){
   <code>
}

Is there a way that this can be presented in a neater way, for example:

function stuff(){
   ...
   .then(result => *continue*)
   <script goes here>
}

Thanks in advance

Assorted
  • 41
  • 1
  • 6
  • 2
    Use `async`/`await`? [What are asynchronous functions in JavaScript? What is "async" and "await" in JavaScript?](https://stackoverflow.com/q/62196932) – VLAZ May 03 '22 at 10:20

1 Answers1

2

I would suggest you to use async/await instead of .then().

Your code would look something like:

// your function need to be async in order to use await keyword
async function stuff(){
try {
//await
const res = await fetch(url);
// next line will only execute when above fetch is complete
const json = res.json()

*Do Your other stuff here*

} catch (e) {
console.log("Err",e)
  }
}

You can read more about async/await here.

Anurag Parmar
  • 252
  • 2
  • 12
  • Thank you! I have really just started in Javascript and I really don't know much about await and async. – Assorted May 03 '22 at 11:05