【问题标题】:async/await - try ... catch inside $.whenasync/await - 尝试...在 $.when 中捕获
【发布时间】:2018-04-20 06:10:13
【问题描述】:

我正在处理一个需要对各种 API 端点进行多次 AJAX 调用的小项目。前三个依次需要彼此的数据,后三个可以独立运行,因为它们与前三个没有任何关系。

这是我对 async/await 的第一次重大尝试,并且实际上将 Promise 用于其预期目的,我对如何处理任何异常感到困惑。我们使用 Vue.js 作为我们的前端框架并使用 JSON 响应。

我用这个函数调用包含我的请求的函数:

fetchAllData: async function() {
    await this.getList()
    await this.getSecondListRelatedToFirst()
    await this.getThirdListRelatedToFirstAndSecond()
    this.getDateRange()
    getConversions()
    getVolumes()
}

请求现在的运行方式:

this.getList()
|------------> this.getSecondListRelatedToFirst()
              |----------> this.getThirdListRelatedToFirstAndSecond()
              |------> this.getDateRange()
              |------> getConversions()
              |------> getVolumes()

this.getList() 运行,然后 this.getSecondListRelatedToFirst()this.getList() 解析时运行,最后四个在 this.getSecondListRelatedToFirst() 解析时运行。

请求的结构都与此非常相似:

getList: function () {
    return $.ajax({
        type: "GET",
        url: '/api/endpoint',
        dataType: 'json',
        data: {
            param_one  : param_one,
            param_two  : param_two,
            param_three: param_three,
            ...
        }
    })
    .then(function(data, status, xhr) {
         let temp = _.map(data, function (d) {
             return {
                 // map some data here         
             }
         }.bind(this));

    }, function(jqXhr, textStatus, errorThrown) {
                console.error(errorThrown);
    })
    .catch(function(error){
         console.log.bind(error)
})

基本思想是,一旦响应从服务器返回,我将数据处理成更容易被 Vue 使用的东西,并随着页面的渲染而移动。

回到第一个函数fetchAllData,它在mounted 生命周期属性中调用,如下所示:

$.when( this.fetchAllData() )
 .then( function() {
    // do some other stuff
 })
 .fail(
      console.log.bind(console);
 );

这就是我的问题所在。考虑到我在 AJAX 级别进行错误捕获(使用 then、catch 块),我是否也需要在这里进行错误捕获?如果是这样,我将如何在 $.when 块中实现这一点?还是在执行时最后的fail 语句就足够了?

这个问题可能是因为阅读了太多用例而没有足够的 Vue.js 和 async/await 经验,我只需要澄清一下这种场景的最佳实践。感谢您的指导!

【问题讨论】:

    标签: javascript vue.js async-await try-catch


    【解决方案1】:

    我认为您需要查看MDN documentation

    var response = await promisedFunction().catch((err) => { console.log(err); });
    // response will be undefined if the promise is rejected
    

    也许它会回答你的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-14
      • 1970-01-01
      • 2017-07-19
      • 2020-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多