Vuex Action:解决嵌套承诺的最佳方法

时间:2020-02-05 10:15:49

标签: vue.js vuejs2 promise vuex aws-amplify

我是JavaScript,vue.js和vuex的新手。

我正在尝试在vuex状态数组中维护图像资产URL的列表。资产位于s3存储桶中,我正在使用放大框架来访问它。

据我所知,我必须首先列出资产以获得可用的密钥。 Storage.list('assets/'),然后我需要致电Storage.get()返回URL。这两个调用都返回Promises。

我当前的vuex模块看起来像这样。

state: {
    imageAssets: []
},

getters:{
    collection: state => state.imageAssets,
    // assetByKey: state => key => {

    // }
},

mutations: {
    setImageAssets: (state, imageAssets) => {
        Vue.set(state, 'imageAssets', imageAssets);
    },
    addImageAsset: (state, imageUrl) => {
        state.imageAssets.push(imageUrl);
    }

},

actions: {
    listAssetsS3 : (context) => {
        return new Promise((resolve, reject) => {
            Storage.list('assets/')
                .then(result => {
                        result.filter(el => /.*\.png/g.test(el.key))
                              .forEach(el => {
                            Storage.get(el.key).then(res => 
                                {
                                    context.commit('addImageAsset', res);
                                    resolve(res)
                                })
                            }) 
                },
                error => {
                    logger.debug('ERROR', error)
                    reject(error);
                })
        })
    },    

这有效,但我想知道这是否是正确的处理方式。我知道该行动需要兑现承诺。但是在这种情况下,我对我的resolve命令的有效性有些困惑,并且还想知道我的解决方案是否最佳并且适合vue / vuex应用程序的范例?

非常欢迎您提出任何提示,更正或一般建议。

非常感谢, M

0 个答案:

没有答案