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


4
  • 2
    Does this answer your question? How do I return the response from an asynchronous call? Commented Nov 6, 2019 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... Commented Nov 6, 2019 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. Commented Nov 6, 2019 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. Commented Nov 6, 2019 at 15:25

1 Answer 1

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"
});
Sign up to request clarification or add additional context in comments.

1 Comment

Please add some explanation to your answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.