2

I am making a function that checks is there an image in url and it should return true or false depending of success.

var image = this.checkImage(imageUrl);
console.log('image: ' + image);

async checkImage(image){
  var a;
  await RNFetchBlob.fetch('GET', image)
  .then((res) => {
     a = true;
  })
  .catch((errorMessage, statusCode) => {
     a = false;
  })

  console.log(a);
  return a;
}

console.log(a); returns true or false so that works allright, but console.log('image: ' + image); returns [object Object]

Can you figure out what is wrong in my code?

V. Vais
  • 88
  • 1
  • 6
  • parse it to a string `console.log('image: ' + JSON.stringify(image))` – Jonathan Portorreal Feb 23 '17 at 08:33
  • 2
    It's kinda expected to have that output if you ask me ... – KarelG Feb 23 '17 at 08:34
  • 1
    Async functions always return a promise. – Lux Feb 23 '17 at 08:35
  • 5
    [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – async/await don't turn asynchronous functions into synchronous functions. – JJJ Feb 23 '17 at 08:37

3 Answers3

0

Async functions return Promises, and thus your image variable is a Promise. Handle it as such:

this.checkImage(imageUrl).then(function (image) {
    console.log(image)
})

In my browser, Promise.resolve(value).toString() returns '[object Promise]' rather than '[object Object]' as you described, but I believe that the underlying issue remains the same regardless of the Promise implementation.

As a side note, I believe asynchronous functions should be declared as async function name() {} rather than async name() {}.

gyre
  • 16,369
  • 3
  • 37
  • 47
0

an Async Function always returns a Promise. That promise is rejected in the case of uncaught exceptions, and it’s otherwise resolved to the return value of the async function.

this.checkImage(imageUrl).then(image => console.log('image: ' + image));;


async checkImage(image){
  var a = await RNFetchBlob.fetch('GET', image)
  .then((res) => {
     a = true;
  })
  .catch((errorMessage, statusCode) => {
     a = false;
  })

  return a;
}
Gaurav joshi
  • 1,743
  • 1
  • 14
  • 28
0

The problem here is that you have to await the call to checkImage, otherwise it immediately returns a promise.

const image = {
  async getImage() {
    // without this await the checkImage fn immediately return a promise
    var image = await this.checkImage('someURL');
    console.log('image: ' + image);
  }

  async checkImage(image){
    var a;
    await fetch(image)
      .then((res) => {
        a = true;
      })
      .catch((errorMessage, statusCode) => {
        a = false;
      })

    console.log(a);
    return a;
  }
}

You can put console.log in then and catch to see the order in which they are executed with and without the await