简体   繁体   中英

How do this chain of promises without async/await by using then, catch

  1. I should fetch from the server some information.
  2. If information isn't valid I should fetch information by using another query to the server.
  3. If information isn't valid again I should return a rejected promise(error)
  4. If information was valid on 2 or 3 steps I should save it and return resolved promise to calling code

I've done this by using async/await. But I can't understand how to do this using then and catch blocks.

My code:

this.loadSettingReport()
  .then(() => {
    console.log("Success!")
  })
  .catch((error) => {
    console.log("Promise worked with Error")
    console.log(error)
  })

//...

async loadSettingReport() {
  console.log("SettingReport - Company")
  let response = await findAllSettingsReports(this.$axios, /*someParameters*/) //request via axios - return promise
  let data = response.data
  console.log(data)
  if(data.length === 0) {
    console.log("SettingReport - Common")
    response = await findAllSettingsReports(this.$axios, /*other someParameters*/) //request via axios  - return promise
    data = response.data
    if (data.length === 0) {
      console.log("SettingReport - NotFound")
      throw new Error("SettingReport - NotFound")
    }
  }
  //Do something...
},

//...

export const findAllSettingsReports = function($axios, params = {}){
  return $axios.get(url, isEmpty(params) ? {} : { params: params })
}

UPDATE: My final variant is:

loadSettingReport() {
   return findAllSettingsReports(this.$axios, {variant: "ID", rows: true, search: "common:false,company.id:"+this.company.id + ",typeReport.id:" + this.typeReportId})
      .then(response => {
         if(response.data.length == 0) {
            return findAllSettingsReports(this.$axios, {variant: "ID",  rows: true, search: "common:true,typeReport.id:" + this.typeReportId})
         }
         return response
      })
      .then(response => {
         if(response.data.length == 0) {
            throw new Error("Настройка отчетов не найдена")
         }
         this.setting = response.data[0]
         return response.data[0]
      })
}

The general rule is to change all

someVar = await somePromise;
// more lines

into

return somePromise.then((someVar) => {
  // more lines
});

You're trying to do two separate things, it looks like:

  • Retrieve the data (retry once)

  • Do something with the data

To be less repetitive, and to have them play nicely with .then syntax, put those into separate functions:

loadSettingReport(retries = 1) {
  return findAllSettingsReports(this.$axios, /*someParameters*/).then((response) => {
    if(response.data.length === 0) {
      if (retries === 0) {
        throw new Error("SettingReport - NotFound");
      }
      return this.loadSettingReport(retries - 1);
    }
    return response;
  });
},
processSettingsReport(response) {
  // do something
}

and

this.loadSettingReport()
  .then(response => this.processSettingsReport(response))
  .catch((error) => {
    console.log("Promise worked with Error")
    console.log(error)
  })

At the expense of passing a successful result down a promise chain step, you could replace the async function with something like

const loadSettingReport = () => {
    return findAllSettingsReports(this.$axios( /*someParameters*/ ))
       .then (response => {
           if( response.data) {
              return response;
           }
           return findAllSettingsReports(this.$axios( /*other Parameters*/ ))
       })
       .then (response => {
           if( !response.data) {
               console.log("SettingReport - NotFound")
               throw new Error("SettingReport - NotFound")
           }

           // .... do something with response 

           return something;
       });
};

The returned promise fulfills with the return something value or is rejected with an error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM