javascript - async/await - 尝试...在 $.when 内捕获

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

我正在开发一个小型项目,该项目需要对各种 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 block ),我是否也需要在这里进行错误捕获?如果是这样,我将如何在 $.when block 中实现这一点?或者此时执行的最终 fail 语句是否足够?

这个问题可能是因为阅读了太多的用例,并且对 Vue.js 和 async/await 的经验不足,我只需要对此类场景的最佳实践进行一些澄清。感谢您的指导!

最佳答案

我认为你需要看看 MDN documentation .

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

也许它会回答你的问题。

关于javascript - async/await - 尝试...在 $.when 内捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48833008/

相关文章:

vue.js - Vee Validate 阻止我的组件运行,errors.first 故障

c# - 为什么等待后 HttpContext.Current 为空?

javascript - HTML 数组上的淡入/淡出

javascript - Vuejs 无法加载 svg 图片?

javascript - 将图像放置在随机位置但不要超出屏幕

javascript - 处理计算属性中的意外副作用 - VueJS

c# - 异步匿名无参数方法作为方法参数

javascript - 如何打破循环 onClick ReactJS

javascript - Jasmine-node 未显示测试结果

javascript - 使用 ECMAScript 5 获取/设置属性并揭示模块模式