0

As I'm new to Promises/async/await and modern JavaScript, I'm a bit confused about how could it be possible to return value of "then" function for parent function:

 async function f1() {
            return 1;
        }

        function f2() {
            f1().then((f1_output) => {
                console.log(f1_output);//write 1 on console
                return f1_output;
            })
        }

        let f2_output = f2();//I expect to get 1 (f1_output)
        console.log(f2_output);//undefined

It is a part of web scraping project in NodeJS, f1 is actually fetch some data from web, f2 apply some modification on result. I don't have access to f1 and I can't change it! In other hand, I can change/build f2 whatever I want. Btw, sorry for my bad English! :)

  • f2 function doesn't have an explicit return statement when a function doesn't have a return statement or if the return statement is missing inside an asynchronous function, the function will implicitly return undefined. – Hasan Raza Jun 27 '23 at 13:12
  • @SoftwareEngineer Thanks for your reply, anyway, how could I return it as f2_output? , so that I can use it in global scope? – Mostafa Abasinejad Jun 27 '23 at 13:22
  • 1
    you can modify f2 to return a promise and use async/await syntax to handle the asynchronous operation – Hasan Raza Jun 27 '23 at 13:24
  • kindly marked this solution as solved if you got your answer through me – Hasan Raza Jun 27 '23 at 13:25
  • @SoftwareEngineer — To make a question as solved, the OP must accept an answer, which they can't do because there are no answers (and there can't be any because the question is closed since this is a FAQ). – Quentin Jun 27 '23 at 13:34
  • Sorry I wasn't aware of it – Hasan Raza Jun 27 '23 at 13:35

0 Answers0