从导入的模块中返回数据,该模块是异步的。

huangapple go评论63阅读模式
英文:

Return data from imported module which is Asynchronous

问题

I have read many articles relating my issue such as (https://stackoverflow.com/questions/55476302/returning-a-variable-from-a-function-in-an-imported-module and https://stackoverflow.com/questions/72801517/nodejs-cant-returned-data-from-imported-module is undefined) I also read (https://stackoverflow.com/questions/23667086/why-is-my variable unaltered after I modify it inside of a function asynchron and https://stackoverflow.com/questions/14220321/how do I return the response from an asynchronous call) but im still stuck, I tried all the solutions by my issue is still persistent.

I am new to JS and am new to promises and await, which is mainly why I am confused. I am using a simple mongoose function,

//Find and return user object function
async function findUser(associatedUser) {
try {
//Find a user based on given info
const foundUser = await User.find({ associatedUser: associatedUser });
//It returns a list of object, but usually its just one object. So we just get that one object
const foundUserObject = foundUser.find(o => o.associatedUser == associatedUser);
return foundUserObject;
} catch (err) {
console.log(err);
process.exit(1);
}
}

The function finds a user based on their name and returns it, in the local file I can access the function return value like this

foundUserObject = await findUser(associatedUser);

and it works.

However when I import the module, and give an input

const MongoDBModule = require('./index');

MongoDBModule.findUser(associatedUserPrompt)

It always returns undefined, when I try to make my return a promise in the original code

return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(FoundUserObject);
}, 5000);
});

which is what some links told me to do I still get undefined; I think its because im returning a static value and not a request but im not too sure

When I try to put the return in an async function I get this error https://stackoverflow.com/questions/60368017/await has no effect on the type of this expression

and when I try to use

MongoDBModule.findUser(associatedUserPrompt).then(value => {
console.log(value);
});

I get

TypeError: Cannot read properties of undefined (reading 'then')
at Object. (D:\Programming Related\MongooseTests\testingimport.js:18:45)
at Module._compile (node:internal/modules/cjs/loader:1226:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1280:10)
at Module.load (node:internal/modules/cjs/loader:1089:32)
at Module._load (node:internal/modules/cjs/loader:930:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:23:47

Node.js v18.14.0

From what I read this has something to do with a synchronous function trying to access an asynchronous return function, and I read many posts and tried everything but I'm really stuck. I just need to know how to not return undefined and return the object which I'm supposed to be getting.

This is what I'm supposed to get --

{
associatedUser: '971567800902@c.us',
currentContext: 'none',
name: 'none',
email: 'none',
subject: 'none',
budget: 'none',
phone: 'none',
message: 'none',
mailinglist: false,
_id: new ObjectId("63efda10621fb2247732d115"),
__v: 0
}

How I export the function

module.exports = {
findUserAndUpdateValues: function (associatedUser, givenObjectValue, newValue) {
findUserAndUpdateValues(associatedUser, givenObjectValue, newValue);
},

createUser: function (associatedUser, currentContext, name, email, subject, budget, phone, message, mailinglist) {
createUser(associatedUser, currentContext, name, email, subject, budget, phone, message, mailinglist);
},

findUser: function (associatedUser) {
findUser(associatedUser);
},
};

英文:

I have read many articles relating my issue such as (https://stackoverflow.com/questions/55476302/returning-a-variable-from-a-function-in-an-imported-module and https://stackoverflow.com/questions/72801517/nodejs-cant-returned-data-from-imported-module-is-undefined) I also read (https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron and https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) but im still stuck, I tried all the solutions by my issue is still persistent.

I am new to JS and am new to promises and await, which is mainly why I am confused.
I am using a simple mongoose function,

//Find and return user object function
async function findUser(associatedUser) {
  try {
    //Find a user based on given info
    const foundUser = await User.find({ associatedUser: associatedUser });
    //It returns a list of object, but usually its just one object. So we just get that one object
    const foundUserObject = foundUser.find(o => o.associatedUser == associatedUser);
    return foundUserObject;
  } catch (err) {
    console.log(err);
    process.exit(1);
  }
}

The function finds a user based on their name and returns it, in the local file I can access the function return value like this

foundUserObject = await findUser(associatedUser);

and it works.

However when I import the module, and give an input

const MongoDBModule = require('./index');

MongoDBModule.findUser(associatedUserPrompt)

It always returns undefined, when I try to make my return a promise in the original code

return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(FoundUserObject);
        }, 5000);
    });

which is what some links told me to do I still get undefined; I think its because im returning a static value and not a request but im not too sure

When I try to put the return in an async function I get this error https://stackoverflow.com/questions/60368017/await-has-no-effect-on-the-type-of-this-expression

and when I try to use

MongoDBModule.findUser(associatedUserPrompt).then(value => {
  console.log(value);
});

I get

TypeError: Cannot read properties of undefined (reading 'then')
    at Object.<anonymous> (D:\Programming Related\MongooseTests\testingimport.js:18:45)  
    at Module._compile (node:internal/modules/cjs/loader:1226:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1280:10)
    at Module.load (node:internal/modules/cjs/loader:1089:32)
    at Module._load (node:internal/modules/cjs/loader:930:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:23:47

Node.js v18.14.0

From what I read this has something to do with a synchronous function trying to access an asynchronous return function, and I read many posts and tried everything but I'm really stuck. I just need to know how to not return undefined and return the object which I'm supposed to be getting.

This is what I'm supposed to get --

{
  associatedUser: '971567800902@c.us',
  currentContext: 'none',
  name: 'none',
  email: 'none',
  subject: 'none',
  budget: 'none',
  phone: 'none',
  message: 'none',
  mailinglist: false,
  _id: new ObjectId("63efda10621fb2247732d115"),
  __v: 0
}

How I export the function

module.exports = {
  findUserAndUpdateValues: function (associatedUser, givenObjectValue, newValue) {
    findUserAndUpdateValues(associatedUser, givenObjectValue, newValue);
  },

  createUser: function (associatedUser, currentContext, name, email, subject, budget, phone, message, mailinglist) {
    createUser(associatedUser, currentContext, name, email, subject, budget, phone, message, mailinglist);
  },

  findUser: function (associatedUser) {
    findUser(associatedUser);
  },
};

答案1

得分: 2

要么添加丢失的 return

module.exports = {
  // ...
  findUser: function (associatedUser) {
    return findUser(associatedUser);
  },
};

要么根本不创建包装函数:

module.exports = {
  // ...
  findUser
};
英文:

Either add the missing return

module.exports = {
  // ...
  findUser: function (associatedUser) {
    return findUser(associatedUser);
  },
};

Or don't create a wrapper function at all

module.exports = {
  // ...
  findUser
};

huangapple
  • 本文由 发表于 2023年2月18日 03:53:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75488699.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定