Async函数返回[object Promise],需返回实际值的Electron-Vue+NeDB问题
解决Async函数返回[object Promise]而非实际值的问题
我完全懂你遇到的困扰——async函数本身就会返回Promise对象,Vue模板里直接调用它的话,只会显示这个Promise的字符串形式[object Promise],而且模板里没法直接用await,因为渲染上下文根本不是async函数。另外看你的代码,testNedb3函数里的Promise链也没正确返回结果,这也是拿不到实际值的关键原因之一。
下面是具体的修复步骤:
1. 让testNedb3正确返回Promise结果
你的testNedb3是async函数,但里面用了嵌套的then链,却没把最终结果返回出去。而且用await替代then链会让代码更简洁易读,还能确保函数返回最终的处理结果。另外,你的flattenMemAsync和filterByNameIdAsnc其实没必要包装成Promise,因为里面的数组操作都是同步的,完全可以简化:
修改后的testNedb3函数:
async testNedb3(id) { // 简化扁平化操作,同步完成 const flattenMem = (arr) => { return Array.prototype.concat.apply([], arr.map(item => item.members)); }; // 简化过滤操作,同步完成 const filterByNameId = (arr) => { return arr.filter(member => member.nameId === id); }; // 用await替代嵌套then链 const docs = await this.dbFindAsync2(this.$db, { 'members.nameId': id }, { 'members': 1, _id: 0 }); const flatMembers = flattenMem(docs); const result = filterByNameId(flatMembers); console.log('result', result); console.log('result_firstname', result[0]?.firstName); // 用可选链避免空值报错 return result; }
2. 不要在模板中直接调用async函数,通过数据驱动渲染
Vue模板没法直接处理Promise,我们需要在组件的生命周期钩子(比如created或mounted)里调用async函数,把结果赋值给data里的变量,再让模板渲染这个变量:
首先在组件的data中定义存储结果的变量:
data() { return { testResult: [] // 初始化为空数组 }; }
然后在created钩子中调用函数并赋值:
async created() { this.testResult = await this.testNedb3('NDId6sekw6VYLmnc'); }
最后修改模板,渲染testResult:
<template> <div> {{ testResult }} <!-- 如果要显示具体属性,加个判断避免空值报错 --> {{ testResult.length > 0 ? testResult[0].firstName : '暂无数据' }} </div> </template>
3. 为什么原来的方法行不通?
- 直接在模板里调用
testNedb3():因为async函数返回的是Promise,模板会直接把这个对象转成字符串[object Promise]。 - 尝试
{{ testNedb3().then(value => value) }}:then本身也会返回Promise,所以结果还是一样的。 - 用
await在模板里:模板的表达式执行环境不是async函数,自然会抛出语法错误。
这样修改后,你就能在页面上看到正确的结果了,而且代码结构更清晰,还避免了不必要的Promise嵌套。
内容的提问来源于stack exchange,提问作者user4565857
相关产品推荐
相关产品推荐

