1

I'm using node.js, and since this is my first time working with both javascript and asynchronous programming, things are going pretty rough. So I have this piece of code that outputs the result of a resolved promise:

promise.then(function(result) {
   console.log(result)
});
// outputs result

It works as intended, but I don't need the result in the console, I need to pass it into some variable so that it can be used later. Like this:

promise.then(function(result) {
   //magic
});
//maybe some more magic
console.log(myvar)
// outputs result 

Is there any way to do this? Thank you in advance. Please pardon my grammar, English isn't my native tongue.

  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – mpm Sep 17 '18 at 10:50

2 Answers2

2

If you're using Node.js version 8 or higher, you can use async/await to basically wait for the promise value:

async function foo() {
  try {
    const result = await someFunctionReturningPromise();
    console.log(result); // log when the promise is resolved
  } catch(err) {
    console.error(err); // error when the promise is rejected
  }
}
Petr Broz
  • 8,891
  • 2
  • 15
  • 24
0

You can return a Promise from a function with either resolve or rejected value , then use then to do anything with the value

function abc() {

  return new Promise((resolve, reject) => {
    return resolve([1, 2, 3])
  });
}

abc().then(function(data) {
  console.log(data)

})
brk
  • 48,835
  • 10
  • 56
  • 78