-2

I am learning async await using node js

var testasync = async () =>
{

const result1 = await returnone();

return result1;
}

testasync().then((name)=>{
    console.log(name);
}).catch((e) =>{
    console.log(e);
});


var returnone = () =>{
    return new Promise((resolve,reject)=>
{
    setTimeout(()=>{
        resolve('1');
    },2000)
})
}

It fails with returnone is not a function. What am i doing wrong? calling the function just by itself work

returnone().then((name1) => {
    console.log(name1)
})

Just calling the above code works

alangilbi
  • 321
  • 5
  • 17
  • let test = await returnone should work. – Izio May 14 '18 at 15:31
  • Possible duplicate of [Does a Javascript function have to be defined before calling it?](https://stackoverflow.com/questions/9973461/does-a-javascript-function-have-to-be-defined-before-calling-it) – kgangadhar May 14 '18 at 15:43

2 Answers2

1

You are assigning the function to the variable returnone at the end of the code, but you are trying to call that function before this assignment. You have two options to fix the code:

Option 1

Use a function declaration; this way, the function is hoisted and you can use it right from the start:

var testasync = async () => {
  const result1 = await returnone();  
  return result1;
}

testasync().then((name) => {
  console.log(name);
}).catch((e) => {
  console.log(e);
});

function returnone() {
  return new Promise((resolve,reject) => {
    setTimeout(() => {
      resolve('1');
    }, 2000)
  })
}

Option 2

Assign the function to the variable before you try to call it:

var returnone = () => {
  return new Promise((resolve,reject) => {
    setTimeout(() => {
      resolve('1');
    }, 2000)
  })
}

var testasync = async () => {
  const result1 = await returnone();  
  return result1;
}

testasync().then((name) => {
  console.log(name);
}).catch((e) => {
  console.log(e);
});
Patrick Hund
  • 19,163
  • 11
  • 66
  • 95
  • Make sense, I was just trying to rewrite some and forgot that the defintion of the function was after the call – alangilbi May 14 '18 at 15:42
1

The reason you are getting this error because of hoisting. Your code seen by JS would look like this

var returnone;
var testasync = async () => {
  const result1 = await returnone();  
  return result1;
}

testasync().then((name) => {
  console.log(name);
}).catch((e) => {
  console.log(e);
});

returnone = () => {
  return new Promise((resolve,reject) => {
    setTimeout(() => {
      resolve('1');
    }, 2000)
  })
}

So the value of returnone is undefined.

AbhinavD
  • 6,892
  • 5
  • 30
  • 40