Javascript 异步函数返回 [object Promise]

use*_*857 3 javascript promise vue.js electron-vue

Async函数返回,[object Promise]但期望的行为是返回实际值。我可以从中获取价值console.log

我想这是该函数的预期行为,但我不知道如何修复我的代码。

这是使用 electro-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
          })
        })
      })
    },
Run Code Online (Sandbox Code Playgroud)

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”。”。

任何评论都可以帮助我。谢谢。

fil*_*ipe 12

不要在视图中调用异步方法。

\n

当您将方法标记为异步时,它将返回一个承诺,因此,返回承诺并同时将其标记为异步是没有意义的。

\n

您应该等待来自创建的异步方法或承诺或其他合适的生命周期挂钩,并将结果保存在 component\xe2\x80\x99s 数据中,然后渲染该数据。

\n

另外,看看vue-promised插件。

\n