skip to Main Content

I can’t understand why I am getting the error in the subject:

var a = async function(){
    await setTimeout(function(){console.log('Hi');},2000);
    return(7);
  }.then((res)=>{console.log(res);});
  
  console.log(a());

It’s just a test to learn to work with async/await and promises, my code shouldn’t do anything meaningful

2

Answers


  1. You should call .then on a Promise to get the result after it completes. Currently, you are attempting to call .then on a function, which does not have this method. You would need to call the async function to get a Promise, which you can then wait for.

    For example:

    (async function() {
      return 7;
    })()/* note these parentheses */.then(console.log);

    Note that await does not make sense with setTimeout, as it does not return a Promise.

    Login or Signup to reply.
  2. You can use this as a sample for trying out async/await with Promises

    const a = async function(){
        const samplePromise = new Promise((resolve,reject)=>{
            setTimeout(()=>{
                console.log('Hi')
                resolve(true)
            },2000)
        });
        await samplePromise;
    }
    
    a().then(()=>{
        console.log('a function is implemented')
    })

    Few points to note:

    • You can await only Promises, setTimeout does not create Promises rather it is used to imitate a time taking process.
    • An async function always return Promises.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search