简体   繁体   English

升级.then.catch 到 async await 并尝试 catch

[英]Upgrade .then .catch to async await and try catch

I'm tryng to upgrade this code for a better maintenance, this code uploads two images to a server, i know it's possible to get rid of those.catch, by applying async await functions, and try catch blocks, but it's pretty confusing for me, any help will be apreciated.我正在尝试升级此代码以获得更好的维护,此代码将两个图像上传到服务器,我知道可以通过应用异步等待函数来摆脱那些.catch,并尝试捕获块,但这对于我,任何帮助将不胜感激。

 this._uploadService.makeFileRequest(Global.url + "/upload-image1/" + response.product._id, [], this.filesToUpload1, 'image').then((result: Product) => { this.filesToUpload1 = null; this._uploadService.makeFileRequest(Global.url + "/upload-image/" + response.product._id, [], this.filesToUpload, 'image').then((result: Product) => { this.filesToUpload = null; setTimeout( () => this._router.navigate(['/detail', this.saveProduct._id]), 800 ); }).catch(err => { console.log(err); this._router.navigate(['/detail', this.saveProduct._id]); }) }).catch(err => { console.log(err); this._router.navigate(['/detail', this.saveProduct._id]); })

I suggest using a pen and paper to draw a block diagram for the logic involved, ie which api gets called first, with what kind of data, then which api comes afterwards;我建议用纸笔画出涉及的逻辑框图,即先调用哪个api,用什么样的数据,然后再调用哪个api; also include any logical conditionals through branching.还包括通过分支的任何逻辑条件。

After that, you should attempt to write something like之后,您应该尝试编写类似

const aggregateFunction = async() => {
  try {
    const someResponse = await callFirstApi(); // return response
    await callSecondApi(someResponse); // use the response of the first api for the second api
    if (someConditional) {
      await callThirdApi(); // response not returned (i.e. when not required)
    }
  } catch (error) { // catch all errors from all await if they're not within another try-catch
    console.log(error);
  }
}

This pattern should eliminate all then and catch blocks.这种模式应该消除所有thencatch块。 If you need more specific error handling for calling say a specific api, wrap function call inside another try-catch block, but everything should still be within the outer try-catch so that all error s will be caught regardless. If you need more specific error handling for calling say a specific api, wrap function call inside another try-catch block, but everything should still be within the outer try-catch so that all error s will be caught regardless.

this._uploadService.makeFileRequest = function(){
    return new Promise(resolve => {
        // do logic of file request
        resolve(true);
    })
}
var waitForTime = function() {
    return new Promise(resolve => {
         setTimeout( () => {
            this._router.navigate(['/detail', this.saveProduct._id]),
            resolve(true)
        }, 800 );    
    })
}
var f = async function(){
  try {
    await this._uploadService.makeFileRequest(Global.url + "/upload-image1/" + response.product._id, [], this.filesToUpload1, 'image');
    await this.fileToUpload1 = null;
    await this._uploadService.makeFileRequest(Global.url + "/upload-image/" + response.product._id, [], this.filesToUpload, 'image')
    await this.fileToUpload = null;
    await waitForTime();
  }
  catch(e) {
    // error logic
  }
}
if (this.filesToUpload1 && this.filesToUpload) {
  f()
}

this might be another cleaner approach with async,await and promise这可能是使用 async、await 和 promise 的另一种更简洁的方法

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

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