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
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)
}
}