Reputation: 988
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
Upvotes: 0
Views: 57
Reputation: 71
Form promise :
var promise1 = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('foo');
}, 300);
});
promise1.then(function(value) {
console.log(value);
// expected output: "foo"
});
Upvotes: 1