【问题标题】:How to export the data present in await如何导出等待中存在的数据
【发布时间】:2019-08-08 05:50:20
【问题描述】:

我正在为承诺、异步/等待而苦苦挣扎。在这里,我想将 gridfs 对象导出到另一个文件,但是当我使用 require 导入它并执行 console.log(gridfs) 时,它会给出一个空对象。任何人都可以帮助我如何导出 gridfs

const mongoose = require('mongoose');

async ()=> {
    await mongoose.connection.on('connected', ()=>{
        const gridfs = require('mongoose-gridfs')({
            collection: 'sharedfiles',
            model: 'SharedFiles',
            mongooseconnection: mongoose.connection
        });
        global.sharedfile = gridfs;
    });
module.exports = sharedfile;
} 

我需要gridfs的文件:

const sharedfile = require('path to above file');
//under another promise
rslt.data.on('end', ()=>{
    console.log(sharedfile);
}

我得到的结果是 {},因为 console.log 在脚本加载之前运行,任何人都可以建议如何修复它。 (我是 Promise 和 async/await 的新手)。

【问题讨论】:

  • mongoose.connection.on真的返回一个 Promise接受回调吗?
  • mongoose.connection.on 返回一个对象并接受回调@Cer
  • 该对象是 Promise 吗?
  • 我不确定,但我认为这是因为它可以由异步函数 @Cert 返回

标签: node.js express mongoose


【解决方案1】:

两件事。

首先,您从未真正调用过匿名异步函数。

其次,您的导出在该函数的范围内,因此它永远不会被设置。因此,您的要求返回 module.export 的空内容“{}”。

试试这样的。

const mongoose = require('mongoose');

module.exports = async ()=> {
    await mongoose.connection.on('connected', ()=>{
        const gridfs = require('mongoose-gridfs')({
            collection: 'sharedfiles',
            model: 'SharedFiles',
            mongooseconnection: mongoose.connection
        });
     global.sharedfile = gridfs;
     return gridfs;
    });
} 

然后,您的导出为需要的代码提供异步函数(一个 Promise)。您使用() 调用它并使用.next 来处理其返回的结果。

require('path to above file') ()
   .next( 
      function (gridfs) {
        console.log (gridfs)
      } )
   .catch (...)

或者您可以先请求它,然后再调用它。

const getGridFs = require('path to above file')
...
getGridFs ( )
  .next (gridfs => {console.log(gridfs)})
  .catch (error => {console.error(error)})

耐心点:你会弄明白的。

【讨论】:

  • 这是说 getGridFs().next 不是一个函数。所以,我尝试了 getGridFs().then((rslt)=> console.log(rslt)) 但得到了一个未定义的值,如果我在异步函数本身中控制台 gridfs,则情况并非如此。
猜你喜欢
  • 2019-09-17
  • 1970-01-01
  • 1970-01-01
  • 2011-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多