-2

I am using the function fetch to get data from a url by doing

function fetchData(){
     return fetch(url).then(function(response){
         return response.json();
     })
    .catch((error) => {
       console.error(error);
     }); 
}


Promise {_45: 0, _81: 0, _65: null, _54: null}
_45:0
_54:null
_65:{products: Array(50)}
_81:1
__proto__:Object

How do I access the 'products' in this promise. I tried doing json._65 but that didn't give me the json containing products.

Thanks in advance.

Basim Sahaf
  • 33
  • 1
  • 7
  • I would say you are most likely missing the point of a Promise. In general, in javascript, if a property is prefixed with an underscore, it is not meant to be dereferenced directly. – rmlan Jan 03 '18 at 19:58
  • Please provide relevant code as well...https://stackoverflow.com/help/how-to-ask – Anirudh Mangalvedhekar Jan 03 '18 at 19:58
  • Yes I am new to Javascript. Any help to access the products array would be appreciated. Thanks – Basim Sahaf Jan 03 '18 at 19:59
  • 2
    You don't access a promise directly. You use methods like `.then()` to call a function, it receives the object that the promise resolves to as an argument. – Barmar Jan 03 '18 at 20:00
  • Assuming this is an ECMA promise object, have a look at the [Promise docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). They may be helpful. – rmlan Jan 03 '18 at 20:01
  • 1
    This doesn't look like a promise. At best a promise with obfuscated property names. – Bergi Jan 03 '18 at 20:02

1 Answers1

0

You cannot access the result of a promise. You have to wait for it, then the promise will pass it to your callback:

fetchData().then(result => {
    console.log(result); // will happen later
});
console.log("fetching"); // will happen immediately
Bergi
  • 630,263
  • 148
  • 957
  • 1,375