1

React Native Development:

I am in the process of building a react native application and I'm learning the basics needed to understand promises. I am finding it difficult to work out why some things are happening. My biggest issue so far is that the value I return from a promise is not accessible to me. Here is my function and here is the console log:

Function:

getUri(){
    var data = this.apiclient.retrieveImages()
    var outside_uri = data.then((uri) => { console.log('inside => ' + uri); return uri;})
    console.log('outside => ' + outside_uri)
 }

Console log:

outside => [object Object]
inside => https://firebasestorage.googleapis.com/v0/b/facelapse-50017.appspot.com/o/Q…M0p7x1ROK0yIN02%2F001?alt=media&token=31de9def-cd32-4d5c-ad65-f3f65ad76685

A quick observation: The outside is printing before the inside (possibly because of the async nature of a promise).

J Dorrian
  • 206
  • 3
  • 15
  • 3
    Possible duplicate of [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). *I see no reason to create a new question/answer for this, the above mentioned duplicate also contains a very detailed answer that includes `ES2017+: Promises with async/await`.* – Igor Aug 08 '17 at 14:58
  • @Igor You're assuming that the person knows the details about the functional connection to *asynchronous* calls and probably he didn't. So it would not be entirely correct to mark this as a duplicate, even if it is, technically speaking. This is simply another case of where people search (and post) for some specific problem that turn out to be conceptually similar to some other, previously answered, but jargon ridden question. – not2qubit Feb 23 '18 at 21:00

1 Answers1

3

Solution: By making my entire function asyncronous and making the outside_uri await the execution of the promise, the outside was no longer being evaluated before the promise was completed.

async getUri(){
    var data = this.apiclient.retrieveImages()
    var outside_uri = await data.then((uri) => { console.log('inside => ' + uri); return uri;})
    console.log('outside => ' + outside_uri)
 }
J Dorrian
  • 206
  • 3
  • 15
  • 1
    Not sure why this was downvoted, seems like you've gotten one step closer to understanding how promises and asynchronous processes work... An asynchronous process cannot return in a synchronous context. Async-await makes the context asynchronous. The conventional way would be to leave the context synchronous and use a callback to take action when the asynchronous process finishes. – Lennholm Aug 08 '17 at 15:07