【问题标题】:Javascript async function returns [object Promise]Javascript 异步函数返回 [object Promise]
【发布时间】: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 =&gt; {return value}) }},但结果相同。

也改为{{ await testNedb3('NDId6sekw6VYLmnc').then(value =&gt; {return value}) }},但出现错误“解析错误:无法在异步函数外使用关键字'await'。”。

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

【问题讨论】:

    标签: javascript vue.js promise electron-vue


    【解决方案1】:

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

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

    您应该等待来自created 或其他一些合适的lifecycle hook 的异步方法或承诺,并将结果保存在组件的数据中,然后渲染该数据。

    另外,看看vue-promised 插件。

    【讨论】:

      猜你喜欢
      • 2022-11-14
      • 2021-08-01
      • 1970-01-01
      • 2020-07-09
      • 2017-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-13
      相关资源
      最近更新 更多