4

I'm trying to use async/await function following some tutorials but I don't know why always returns

Promise { <pending> }

Here is my code:

function doubleAfter2Seconds(x) {
    return new Promise(resolve => {
        setTimeout(() => {
            console.log(x);
            resolve(x * 2);
        }, 2000);
    });
}
async function get_media_async (media_id) {
    const a = await doubleAfter2Seconds(10);
    return a;
}


exports.get_media = function(media_id){
    var media_url = get_media_async(media_id);
    return media_url;
};

Any help would be appreciated!

Klian
  • 1,520
  • 5
  • 21
  • 32
  • 3
    `async/await` won't magically turn async code into sync one. Once you have something async everything it touches becomes async as well. So your `get_media` function is also async. – Yury Tarabanko Jun 07 '18 at 08:11
  • Possible duplicate of [async/await always returns promise](https://stackoverflow.com/questions/43422932/async-await-always-returns-promise) – Yury Tarabanko Jun 07 '18 at 08:12

1 Answers1

3

You need to do async/await on get_media method as well. It is because you are calling an async function get_media_async from within this method thus this needs to be async as well.

exports.get_media = async function(media_id){
    var media_url = await get_media_async(media_id);
    return media_url;
};
Farhan Tahir
  • 2,096
  • 1
  • 14
  • 27