2

I want to use the async function to bring out a particular value from my database to my the function global so I can use it in other parts of my application.

async function dimension() {
  const result = await Settings.find({_id : "5d7f77d620cf10054ded50bb"},{dimension:1}, (err, res) => {
    if(err) throw new Error(err.message, null);
     const holder = res[0].dimension; 
    return holder;
    console.log(holder) /// this print the expected result, that i want to make global

  });
  return {
    result
  }; 
};



console.log(dimension())

but the console.log of the dimension() gives me this

Promise { <pending> }

instead of the same value that

console.log(holder)

gives me nothing.

Zlatko
  • 18,936
  • 14
  • 70
  • 123
phemieny7
  • 803
  • 7
  • 21

4 Answers4

2

The problem is you are printing the result of dimension() as soon as you call it, but since this function is async, it returns a promise that is not yet resolved.

You do not need to use async/await here. Settings.find() seems to return a Promise. You can just return directly this Promise and use .then() to do something once that promise is resolved.

Like this :

function dimension () {
  return Settings.find({ _id: '5d7f77d620cf10054ded50bb' }, { dimension: 1 }, (err, res) => {
    if (err) {
      throw new Error(err.message, null);
    }
    return res[0].dimension;
  });
}

dimension().then(result => {
  //print the result of dimension()
  console.log(result);
  //if result is a number and you want to add it to other numbers
  var newResult = result + 25 + 45
// the variable "newResult" is now equal to your result + 45 + 25
});

More info on Promises and async/await

Tom
  • 1,357
  • 2
  • 13
  • 32
  • can you help me correct the code, because i don't know where i got it all wrong – phemieny7 Sep 17 '19 at 17:08
  • I updated my answer with some code you can copy/paste, try it and tell me, it should work. But you should really read about `async`/`await`, will be easier and faster for you in the future if you master that :) – Tom Sep 17 '19 at 17:16
  • i got this ```console.log(await dimension()); ^^^^^ SyntaxError: missing ) after argument list ``` – phemieny7 Sep 17 '19 at 17:23
  • thank you @Tom, please one last thing. Assuming it return a number how will i include this number in something like ```25+45+(the return number)``` – phemieny7 Sep 17 '19 at 17:41
  • instead of `console.log(result);` you can do `console.log(25+45+result.holder);` . But if it returns a number you can simplify it even more (I updated my answer again with that). – Tom Sep 17 '19 at 17:49
  • I dont want to console.log it anymore i want to be calling it into my application – phemieny7 Sep 17 '19 at 18:04
  • Well you can store it in a variable. Modified my answer again to reflect that. – Tom Sep 18 '19 at 06:48
  • what if i want to use it like this ```dimension().then(result => { //print the result of dimension() console.log(result); }); var newResult = result + 25 + 45 // outside the function ``` – phemieny7 Sep 18 '19 at 09:21
  • You can't use it directly outside but there are other solutions. However, you should post another question on stackoverflow, the comment section is not convenient enough to answer your problem, it requires more explanation of what you want to do and more space to answer than allowed here. – Tom Sep 18 '19 at 09:49
  • https://stackoverflow.com/questions/57990292/how-to-make-the-result-of-promise-available-to-me-outside-the-scope-and-save-it – phemieny7 Sep 18 '19 at 10:10
  • Yes, it has been marked as duplicate because this question has already been asked and answer. As you can see here: https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call the answer is quite long and complex, could not do it in the comment :) – Tom Sep 18 '19 at 10:27
0

You have to await for your result, like this:

const result = await dimension();
console.log(result);

In that case, you don't even to make the original function async, just write it like this:

function dimension() {
  return Settings.find({_id : "5d7f77d620cf10054ded50bb"},{dimension:1}, (err, res) => {
    if(err) throw new Error(err.message, null);
     const holder = res[0].dimension; 
    return holder;
  });
};


async function myGlobalFunc() {
    const result = await dimension();
    console.log(result);
}

The best way to have this globally available is to just put your function dimension in a file somewhere. Then where you need the value, you just require it and await its value. E.g.

// get-dimension.js 
// ...const Settings = require... comes here
module.exports = function getDimension() {
  return Settings.find({_id : "5d7f77d620cf10054ded50bb"},{dimension:1}, (err, res) => {
    if(err) throw new Error(err.message, null);
     const holder = res[0].dimension; 
    return holder;
  });
}

// your other modules, e.g.
// my-service-handler.js
const getDimesion = require('./get-dimension');

async function myServiceHandler() {
    const dimension = await getDimension();
    // do stuff with dimension.
}
Zlatko
  • 18,936
  • 14
  • 70
  • 123
0

You're using async/await, but you're mixing it with callbacks, this is not desirable as it leads to confusion. It's not clear what you expect to happen in the callback, but return holder; likely doesn't do what you expect it to do, returning from a callback does not work the same way returning from a promise handler works. Your entire implementation should work with promises so that the async/await syntax reads more naturally (as it was intended).

async function dimension() {
    // We're already awaiting the result, no need for a callback...
    // If an error is thrown from Settings.find it is propagated to the caller, 
    // no need to catch and rethrow the error...
    const res = await Settings.find({_id: "5d7f77d620cf10054ded50bb"}, {dimension: 1});
    return {result: res[0].dimension};
}

(async () => {
    try {
        console.log(await dimension());
    } catch (err) {
        console.error(err);
    }
})();
Jake Holzinger
  • 5,783
  • 2
  • 19
  • 33
0

Use dimension().then() in your code then it will work fine.

async function globalDimension() {
  const data = await Users.findOne({ phone: 8109522305 }).exec();
  return data.name;
}

globalDimension().then(data => {
  console.log(data);
});
Ankit Kumar Rajpoot
  • 5,188
  • 2
  • 38
  • 32