0

I am new to Node.js and promises. I have done some work with async/await in C# but I am struggling with getting the return value. I followed an example on stackoverflow and copied it below. I modified it slightly to represent what I am trying to do and it doesn't work. I'm hoping someone can tell me what I am missing. I created two samples: one with a promise and one using async. Thank you for your help!

let bar;
function foo() {
    return new Promise((resolve, reject) => { 
        setTimeout(function () {        
            resolve('wohoo')
        }, 1000)
    })
}

async function foo2() {
    setTimeout(function () {
        return ('wohoo')
    }, 1000);
}

function test3() {
    foo().then(res => {
        bar = res;
        console.log(bar) 
    });
}

async function test4() {
    let bar2 = await foo2();
    console.log('bar2=', bar2);
}

test3();
test4();
console.log('bar=', bar);
console.log('The end.');


The Output:
-----------
bar= undefined
The end.
bar2= undefined
wohoo


PKonstant
  • 834
  • 2
  • 15
  • 32
  • 2
    Does this answer your question? [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) – lealceldeiro Nov 06 '19 at 15:17
  • Part of the problem here might be that you are using the same variable `bar` across several async functions, and it might be changing unexpectedly... – Alexander Nied Nov 06 '19 at 15:20
  • That's the one I referenced. it works if you use foo().then(res => {bar = res; console.log(bar); }); but if you wrap it in a function as I did in test3() it doesn't set bar. – PKonstant Nov 06 '19 at 15:21
  • bar is only used in test3() and bar2 is only used in test4(). Per your suggestion, I made them completely different and still have the same issue. – PKonstant Nov 06 '19 at 15:25

1 Answers1

1

Form promise :

var promise1 = new Promise(function(resolve, reject) {
  setTimeout(function() {
    resolve('foo');
  }, 300);
});

promise1.then(function(value) {
  console.log(value);
  // expected output: "foo"
});