简体   繁体   中英

How to return values from a promise and async / await function in Node.js

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


Form promise:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM