Async函数返回,[object Promise]但所需的行为是返回实际值。我可以从console.log.我想这是该函数的预期行为,但我不知道如何修复我的代码。这是在使用电子 vue 和 NeDB 的 vue.js 代码中。<template> <div> {{ testNedb3('NDId6sekw6VYLmnc') //this is a test by adding specific id }} </div></template><script>import Promise from 'bluebird'export default { methods: { dbFindAsync2: function (db, opt) { return new Promise(function (resolve, reject) { db.find(opt, function (err, doc) { if (err) { reject(err) } else { resolve(doc) } }) }) }, testNedb3: async function (id) { const flattenMemAsync = function (arr) { return new Promise(function (resolve) { Array.prototype.concat.apply( [], arr.map(function (arr) { resolve(arr.members) }) ) }) } const filterByNameIdAsnc = function (arr) { return new Promise(function (resolve) { const result = arr.filter(function (member) { return member.nameId === id }) resolve(result) }) } this.dbFindAsync2( this.$db, { 'members.nameId': id }, { 'members': 1, _id: 0 } ).then(function (res) { const docs = res flattenMemAsync(docs).then(function (res) { const flatMembers = res filterByNameIdAsnc(flatMembers).then(function (res) { console.log('result', res) console.log('result_firstname', res[0].firstName) return res }) }) }) },this.$db正在从 NeDB 获取数据并且数据是二维数组,所以我试图flattenMemAsync通过filterByNameIdAsnc.console.log('result', res)返回数组并console.log('result_firstname', res[0].firstName)返回字符串。我已将调用代码从 更改为{{ testNedb3('NDId6sekw6VYLmnc') }},{{ {{ testNedb3('NDId6sekw6VYLmnc').then(value => {return value}) }}但结果相同。也更改为{{ await testNedb3('NDId6sekw6VYLmnc').then(value => {return value}) }}但我收到错误“解析错误:无法在异步函数外使用关键字 'await'。”。任何评论都可以帮助我。谢谢你。
1 回答

慕田峪9158850
TA贡献1794条经验 获得超7个赞
不要在视图中调用异步方法。
当您将方法标记为异步时,它将返回一个承诺,因此,同时返回一个承诺并将其标记为异步是毫无意义的。
您应该等待来自created或其他一些合适的生命周期钩子的异步方法或承诺,并将结果保存在组件的数据中,然后呈现该数据。
另外,看看vue-promised插件。
添加回答
举报
0/150
提交
取消