0

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?

4
  • See How do I return the response from an asynchronous call? Commented Sep 13, 2019 at 17:56
  • Declare var produImage in main function , add return statement out of promise 'then' chain scope and add to main function body Commented Sep 13, 2019 at 17:58
  • first asynchronous, second, makes no sense to return in a loop....unless you really want to exit on the first iteration. Commented Sep 13, 2019 at 18:29
  • @epascarello yeah really, loop makes no sense. I will clean it. Commented Sep 13, 2019 at 18:42

1 Answer 1

1

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'
});
Sign up to request clarification or add additional context in comments.

13 Comments

You didn't address the second mistake: getImage() call inside the string concatenation.
Fair enough, focused on the title ;-)
@Chris I'm calling it from image tag src="+ getImage() +" after implement above now getting [object Promise] it should be plain url instead
@Kuldeep Edited my answer to show how to deal with that.
@Chris I have result variable where I am concatenating string. Using js getImage().then((imageSrc) => { const html = `<td><img width="50" height="50" src="${imageSrc}"/></td>`; result += html; }); also getting undefined. Any suggestion please?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.