简体   繁体   English

如何使用 then, catch 没有 async/await 的这个承诺链

[英]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如果信息在 2 或 3 个步骤中有效,我应该保存它并返回已解决的对调用代码的承诺

I've done this by using async/await.我已经通过使用 async/await 做到了这一点。 But I can't understand how to do this using then and catch blocks.但我无法理解如何使用 then 和 catch 块来做到这一点。

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:为了减少重复,并让它们与.then语法很好地配合,请将它们放入单独的函数中:

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以将成功的结果传递到承诺链步骤为代价,您可以用类似的东西替换async函数

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.返回的 Promise 满足return something值或因错误而被拒绝。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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