John Bonda
John Bonda

Reputation: 119

Unable to retrieve data from a promise

I am unable to retrieve data from a promise using then(). Where am I going wrong?

async function A(){
    await new Promise((resolve, reject) => setTimeout(()=>{},1000));
    return 45;
}
A().then(data => console.log(data))

I'm running this code with nodejs. I expect the output to print 45. But the program just executes for 1 second and doesn't print anything. If I remove the timeout statement, I am able to print 45. Where am I going wrong?

Upvotes: 0

Views: 272

Answers (3)

narayansharma91
narayansharma91

Reputation: 2353

Function A should return a promise and use async/await along with IFI (Immediate Function Invocation method)

function A(){
        return new Promise((resolve, reject) => setTimeout(()=>{resolve(100)},1000));
    }
    (async () => {
    var data = await A()
    console.log(data)
    })();

Upvotes: 0

Nenad Vracar
Nenad Vracar

Reputation: 122105

You need to resolve your promise and then return can run.

async function A() {
  await new Promise((resolve, reject) => setTimeout(() => resolve(), 1000));
  return 45;
}
A().then(data => console.log(data))

You could also return promise from A function and then use async/await.

function A() {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(45), 1000)
  })
}

(async() => {
  const res = await A();
  console.log(res)
})()

Upvotes: 1

DedaDev
DedaDev

Reputation: 5249

Your function A should return a promise.

function A() {
  return new Promise((resolve, reject) => setTimeout(() => resolve('hello'), 1000));
}
A().then(data => console.log(data))

Upvotes: 1

Related Questions