0

I am a newbie to nodejs and promises, i am trying to fetch some data from json and pass them to other function for further processing, here is my code.

const test = tests.fetchAll().then(test1 => {
    const testsDataArray = JSON.parse(JSON.stringify(test1))
    const testsData = testsDataArray.data
    const testsId = testsData.find(iid => iid.ips === '1.2.3.4')
    // console.log(testsId.id)
    console.log(testsId)
    return testsId.id.toString()
  })

this has a json which is used in the above code

{
  id: 36,
  name: 'p ',
  seats: 10,
  description: 'Test description',
  contact: 'p@xyz.com',
  created_at: '2019-12-31T11:18:19.000Z',
  updated_at: null,
  ips: '1.2.3.4',
  domains: 'xyz.com',
  termination_date: null,
  seats_used: null
}

when I run the following code :

test.then(result => {
    console.log(result)
  })

the output printed on console is '36', where as when i return the same, it returns [object Promise]

test.then(result => {
        console.log(result)
      })
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – jonrsharpe Jan 01 '20 at 20:25

1 Answers1

0

In your code, test is a promise. The ONLY way to get the value from it is is inside a .then() handler or by using await on the promise.

If you add return result to your .then() handler, that just keeps result as the resolved value of the next promise. It doesn't magically make result a regular, non-asynchronous return value.

Please remember that promise.then() returns ANOTHER promise. So, returning a value from a .then() handler just makes it the resolved value of this additional promise that is returned.

So, if you did this:

const p = test.then(result => {
    return result;
});
console.log(p);          // this is still just a promise

All, you've done is made a new promise with test.then() and made result the value of that new promise. You STILL have to use .then() or await on p to get the value from it. You always have to get a value out of a promise with .then() or await no matter how many times you return it from a .then() handler or from an async function.

jfriend00
  • 683,504
  • 96
  • 985
  • 979