Kuldeep Gill
Kuldeep Gill

Reputation: 109

JavaScript function returning value undefined

I'm creating Google Chrome Extension, and declared a function in background.js that is hitting a API and should return a value but it is returning undefined value. Writing console log before return statement has value.

var produImage;

function getImage() {
    fetch('/api/images.json').then(
        function (response) {
            response.json().then(function (data) {
                var dataresponse=data.results;
                for (var obj = 0; obj < dataresponse.length; obj++)
                {
                  produImage=dataresponse[0].url_170x135;
                  //console.log writing value
                  console.log(produImage);
                  //returning undefind
                  return produImage;
                }
            });

        }
    );
}

//call to function
 '<td><img width="50" height="50" src="' + getImage() + '"/></td>'

Issue

console.log(produImage)

giving value

return produImage

returning undefind

Edited

Also tried as suggested by Chris

function getImage() {
    return fetch('/api/images.json').then(
        function (response) {
            return response.json().then(
                function (data) {
                    ;
                    return data.results[0].url_170x135;
                }
            );
        }
    );
}

and then call to function

 getImage().then(function (imageSrc) {
      const html = `<td><img width="50" height="50" src="${imageSrc}"/></td>`;
});

but still I can't concatenate value to var result getting undefined

I want to concatenate like this:

result = `<tr>
<td>${How To concatenate Here}</td>
<td>${dResponse[obj].category_path}</td>
<td>${dResponse[obj].price}</td>
</tr>`;

Please suggest me, how can I get plain result from getImage() that is returning promise object?

Upvotes: 0

Views: 1819

Answers (1)

Chris
Chris

Reputation: 312

You're only returning from the innermost function, not from getImage.

To make this clearer, I would rewrite as follows (hope this is correct, typing from a phone):

async function getImage() {
  const response = await fetch('/api/images.json');

  const data = await response.json();

  return Promise.resolve(data.results[0].url_170x135);
}

Notes:

  • You should add error handling to this
  • The loop you had there was probably legit in the original code, but served no value in what you posted imho

If you cannot use async / await, the following should work:

function getImage() {
  return fetch('/api/images.json').then(
    function (response {
      return response.json().then(
        function (data) {;
          return data.results[0].url_170x135;
        }
      );
    }
  );
} 

Edit

When you resolve the result of the function, use (in an async function)

const html = await `<td><img width="50" height="50" src="${getImage()}"/></td>`;

or (in a non-async function)

getImage().then(function(imageSrc) {
  const html = `<td><img width="50" height="50" src="${imageSrc}"/></td>`;
  // do something with 'html'
});

P.S. I think the code would benefit from using lambdas in general. In my above example, this would be nicer:

getImage().then((imageSrc) => {
  const html = `<td><img width="50" height="50" src="${imageSrc}"/></td>`;
  // do something with 'html'
});

Upvotes: 1

Related Questions