Exporting a function declared inside asynchronous function

DragonBorn

I have a file in which mongoose is setup

const keys = require('../chat/config/keys');
const mongoose = require('mongoose');
const dbURI = keys.mongoURI;
mongoose.connect(dbURI, { useNewUrlParser: true });
mongoose.set('debug', true);

let fetchVideo;

mongoose.connection.once('open', function () {
  console.log('Mongoose default connection open to ' + dbURI);

  let connectToDB = mongoose.connection.db;
  let videoChatDB = connectToDB.collection('videochat');

  fetchVideo = ({ id }) => {
    if (id !== '100') {
      videoChatDB.findOne({'studentID': parseInt(id)}).then((user) => {
        if (user) {
          console.log(user);
          return true;
        } else {
          console.log(user);
          return false;
        }
      });
    }
  }
});


module.exports = { fetchVideo };

And I am requiring that file inside my index.js file like so:

let db = require('./db');

In my index file I have a socket connection and I need to check the database when a new user comes.

socket.on('new-user', async (user) => {
  let checkAvail = await db.fetchVideo(user);
});

But I am getting this error:

TypeError: db.fetchVideo is not a function

I am guessing it is undefined since it is declared inside an asynchronous function.

How would I make this to work?

CertainPerformance

Because the function is created asynchronously, one option is to export a Promise that resolves to fetchVideo function. Because mongoose.connection.once is callback-based, you'll have to transform it into a Promise.

If you want fetchVideo to resolve to something (rather than nothing), you also have to properly chain the findOne call with the promise chain; to fix that, return videoChatDB.findOne....

const fetchVideoProm = new Promise((res, rej) => {
  mongoose.connection.once('open', function () {
    console.log('Mongoose default connection open to ' + dbURI);

    let connectToDB = mongoose.connection.db;
    let videoChatDB = connectToDB.collection('videochat');

    const fetchVideo = ({ id }) => {
      if (id !== '100') {
        return videoChatDB.findOne({'studentID': parseInt(id)}).then((user) => {
          if (user) {
            console.log(user);
            return true;
          } else {
            console.log(user);
            return false;
          }
        });
      }
    }
    res(fetchVideo);
  });
});


module.exports = { fetchVideoProm };

Consume it by awaiting the creation of the fetchVideo function, and then calling it:

socket.on('new-user', async (user) => {
  const fetchVideo = await db.fetchVideoProm;
  const checkAvail = await fetchVideo(user);
});

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

How to return an outer function inside an asynchronous inner function in swift?

分類Dev

how to run mongoose method inside for loop, as mongoose function is asynchronous

分類Dev

Php function appearing not declared

分類Dev

Function pointer "was not declared in this scope"

分類Dev

Asynchronous function with exec ruby

分類Dev

JSHint: Asynchronous function in loop

分類Dev

Arguments of function inside a function

分類Dev

How to pass variable to a function declared in another function

分類Dev

PySide Application with asynchronous function execution

分類Dev

Asynchronous python function to process PHP

分類Dev

Last value of an asynchronous function in loop

分類Dev

Importing a function inside another function

分類Dev

Arrow function and this inside a constructor function

分類Dev

Calling a Function Inside Map Function

分類Dev

How to use variable declared in useEffect() in another function?

分類Dev

Error: conflicting types for function, function declared in header file

分類Dev

C - function inside struct

分類Dev

Functions inside a function in Julia

分類Dev

Calling a function inside itself

分類Dev

cProfile inside a nested function

分類Dev

Generator function inside a component

分類Dev

this in a function inside render()

分類Dev

call function inside setInterval

分類Dev

Function inside component in reactjs

分類Dev

$resource inside in Controller function

分類Dev

If statement inside a function

分類Dev

function inside an object

分類Dev

Promises inside a recursive function

分類Dev

Define a variable inside a function