0
const findNum = async ()=>{
                setTimeout(()=>{
                    return 5;
                },1000)};

const getNum = async ()=>{
                    const  num = await findNum();
                    return num;
                    }
                    
 const number =  getNum();

console.log(number);

number.then((result)=>{
                    console.log(result);
                    });

I tried so many answers from stack overflow,

like the "then" keyword, but it doesn't work!

The result I got was always like this or just some errors

Promise { <pending> }
undefined

how could I get the result out of the Promise?

  • `findNum` doesn't return a promise that resolves to a number. To do it properly see [How to make a promise from setTimeout](https://stackoverflow.com/q/22707475). However, I suspect this might be [an XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) - if you merely tried to emulate a problem you had, then it might not be an issue with how you construct a promise here. – VLAZ Jul 15 '22 at 17:31

1 Answers1

0

The problem you have is that setTimeout has an callback and you return the value to the callback, not to findNum

setTimeout(()=>{
   return 5;
},1000)};

As you can see, there is an anonymous arrow function that you return you value to it.

The problem here is, you cant really make this work with async / await, you should use new Promise here:

const findNum = ()=> new Promise(res => setTimeout(res, 1000, 5))

This should work.

Also, async functions are always returning promises no matter what

bill.gates
  • 14,145
  • 3
  • 19
  • 47