5

I am building a node module which should return a value after processing in node promises.

// module
module.exports.get_data = function(input){

var promise = fn1();
promise
      .then((res) => {
           // process res
         return res; // return processed value from get_data function
      })
}

How can I get this done ?

imacoder
  • 166
  • 1
  • 11
  • How about `let myvar; promise.then((res) => { myvar = res;})` But keep in mind that myvar is almost useless since you have no way of knowing when it has been set, other than checking every now and then, and once you have completed that code you have re-invented promises. So no, don't bother trying to unwrap your promises. That is not the problem. The problem is "when" and that is the problem promises solve. – ippi Jun 17 '18 at 16:40
  • The sane thing to do is to just return the promise. – ippi Jun 17 '18 at 16:47

1 Answers1

1

It's hard to tell what's happening if we can't see what fn1 is or does. But get_data needs to return a promise, not the value there. In fact, that return statement isn't the return statement for get_data, it is the return statement for the unnamed ES6 Arrow Function, which returns res to the promise just to get passed to the next .then() function. It doesn't get passed to get_data at all.

By immediately returning a new Promise, get_data waits until the promise finishes. And whatever calls get_data can call .then() to use that value. Like this:

module.exports.get_data = function(input){
return new Promise((resolve,reject)=>{

    var promise = fn1();
    promise
          .then((res) => {
               // process res
             resolve(res)
          })
    })
}

But all this seems redundant. While I haven't used await in node, it should work the same as other languages. Which means you should be able to do the following

module.exports.get_data = async function(input){
    var res =  await fn1();
    return res
}

Assuming fn1 is a promise...

GalAbra
  • 5,048
  • 4
  • 23
  • 42
  • 1
    You still need the async keyword or that won't work. and then his question is almost the same. How does he get the value in the outermost scope? await the async function? wrap that await in a new async function to make it work? *await that function?* – ippi Jun 17 '18 at 16:35