Home > front end >  Async method doesn't retrieve information in correct order
Async method doesn't retrieve information in correct order

Time:10-05

In Vue.js, I have this method:

async deleteItemFromDb(item_id) {
      const dbUser = this.settings.db_user
      const dbCreds = this.settings.db_creds
      const dbUrl = "http://127.0.0.1:9878/items/"

      const headers = {
        "Content-Type": "application/json",
        "Authorization": "Basic "   btoa(dbUser   ":"   dbCreds)
      }

      let getUrl = dbUrl   item_id
      const projectData = await fetch(getUrl, {
        method: "GET",
        headers: headers,
        mode: "cors",
        credentials: "include"
      })

      let delUrl = dbUrl   await projectData._id   "?rev="   await projectData._rev
      const deleteItem = await fetch(delUrl, {
        method: "DELETE",
        headers: headers,
        mode: "cors",
        credentials: "include"
      })

      console.log("Item deleted from DB:", deleteItem.data)
}

What happens here is that the projectData doesn't report any errors, so the fetch method gets launched properly, but the deleteItem comes back with something like:

DELETE http://127.0.0.1:9878/items/undefined?rev=undefined 404 (Object Not Found)

Also, the console.log returns undefined as the data.

I assume the data doesn't manage to come back soon enough to form the delUrl correctly. But what is the correct order, or rather which variables should be marked here as await?

CodePudding user response:

fetch() needs to be followed up with a call to .json() (or one of the other functions if you're expecting a different data format)

const response = await fetch(getUrl, {  
  method: "GET",
  headers: headers,
  mode: "cors",
  credentials: "include"
})
const data = await response.json();
let delUrl = dbUrl   data._id   "?rev="   data._rev

CodePudding user response:

Remove the await from the below statement

      const projectData = await fetch(getUrl, {
        method: "GET",
        headers: headers,
        mode: "cors",
        credentials: "include"
      }).json(); // change added

      let delUrl = dbUrl   projectData._id   "?rev="   projectData._rev; // removed await
  • Related