0

I am currently having problem await for previous async function being complete before moving onto next function as the next relies on a value from the other. In the example below getData can not be ran before type is defined

app.get("api/v1/demo",async(req,res)=>{
  try{
      const id = req.query.id
      let type = req.query.type
      if(id){
          if(!type || type==="undefined)){
              type = await findType(id)
          }
          if(type && id){   
          const value = await getData(type,id)
          }
          res.status(200).json({
              status: "sucsess",
              geoJson: data.geoJson,
              sorting: data.sorting,
              options: values.sorting
            })
          //MY problem is that getData relies on type not being undefined but how can I make sure to wait for that?

      }catch(err){
        console.log(err)
      }
})

async function findType(id){
    axios.get(
          "https://data.ssb.no/api/v0/dataset/list.json?lang=no"
        ).then((res) => {
          const datasetValue = res.data.datasets.filter((dataset) => dataset.id === id)
          if (datasetValue[0]["tags"].includes("kommuner")) {
            regionType = "kommune"
          }
          else if (datasetValue[0]["tags"].includes("fylker")) {
            regionType = "fylke"
          }
        else{
            return "Failed"
        }
        })
}

matieva
  • 365
  • 4
  • 12
  • 1
    `findType` needs to `return` the promise returned by `axios.get(...)`. (And there's no need to make it `async`, although that doesn't cause a problem.) – Robin Zigmond May 08 '22 at 16:28
  • Change `axios.get(...).then(res => {...})` to `const res = await axios.get(...)` – CherryDT May 08 '22 at 16:32

0 Answers0