调用async修饰的getFile返回Promise而非数组,如何获取目标数组?
核心原因
所有async关键字声明的函数,返回值永远会被自动包装为Promise对象,无法直接在同步上下文里拿到内部返回的原始值。另外你当前的getFile同时混用了async和.then两种异步语法,逻辑冗余。
修复方案
第一步:优化getFile写法(推荐统一用async/await)
const getFile = async (id) => { // 等待异步请求完成 await store.dispatch(Actions.FILE, id) // 直接返回你需要的数组即可,外层会自动包装为Promise return [{ description: store.getters.currentFile.description, url: 'https://test.com/uploads/' + store.getters.currentFile.name }] }
第二步:调用时等待异步执行完成
写法1:async/await(可读性更高)
调用getFile的外层作用域必须为async函数,用await关键字等待结果返回:
// 示例:如果是在框架生命周期/事件回调中,可以这么写 const init = async () => { const defaultValue = await getFile(getCurrent.value[name]) console.log(defaultValue) // 此处输出为数组类型 // 所有依赖defaultValue的逻辑必须写在await之后 } init()
写法2:.then回调
如果你不想修改外层的函数声明,也可以通过then回调取结果:
getFile(getCurrent.value[name]).then(defaultValue => { console.log(defaultValue) // 此处输出为数组类型 // 所有依赖defaultValue的逻辑必须写在回调内部 })
注意:不存在任何办法可以将异步Promise结果直接转为同步值使用,所有依赖该异步结果的逻辑,必须放在await之后或者then回调内部执行,不能在同步上下文里直接获取结果。
内容的提问来源于stack exchange,提问作者nhatimme
相关产品推荐
相关产品推荐

