【发布时间】:2019-10-23 21:42:28
【问题描述】:
Async 函数返回 [object Promise] 但期望的行为是返回实际值。
我可以从console.log 获取值。
我猜这是函数的预期行为,但我不知道如何修复我的代码。
这是在使用 electron-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'。”。
任何评论都可以帮助我。 谢谢。
【问题讨论】:
标签: javascript vue.js promise electron-vue