Home > Blockchain >  Javascript async function instead of new promise
Javascript async function instead of new promise

Time:10-09

I just learnt "async" that "async" ensures that the function returns promise then i tried to make a promise with writing "async" instead of writing "new Promise" and it didn't work out so i want to know is it wrong syntax or it will never work out and i will have to write only new promise?


// This is a code

async function gets(){
    let gets1 = async()=>{
        return 45;
    }
    gets1.then((value)=>{
        console.log(value, "inside gets1")
    })
}
gets()

CodePudding user response:

As already pointed out, you need to call a function fn().then(, not just reference it fn.then(.
Also if you don't use the await, you also don't need the wrapping await

const gets = () => {
  const gets1 = async() => {
    return 45;
  }
  gets1().then((value) => {
    console.log(value, "inside gets1")
  })
};

gets();

Or use await to get rid of Promise.then():

const gets = async () => {
  const gets1 = async() => {
    return 45;
  };
  const value = await gets1();
  console.log(value, "inside gets1")
};

gets();

Make sure to read top to bottom: async Function

CodePudding user response:

You forgot to call the function

It should be gets1().then() and not gets1.then()

async function gets(){
    let gets1 = async()=>{
        return 45;
    }
    gets1().then((value)=>{
        console.log(value, "inside gets1")
    })
}
gets()

CodePudding user response:

The whole thing will work without the outer async function too:

let gets1 = async()=>"msg from gets1";
gets1().then(console.log)

  • Related