1

I want to create a async method that returns an image path like this:

const renderMasterThumb = async (masterAssetId) => {
    const masterAsset = await getAssetByIdAsync(masterAssetId);
    const path = masterAsset.path;
    return path;
  };

then I call the method like this:

<img
    src={`images/${(async () => {
    await getAssetByIdAsync(collection.masterAssetId);
    })()}`}
    alt="master thumb"
/>

However instead of the image path I get a Promise object:

<img src="images/[object Promise]" alt="master thumb">

Does someone know how I can output the value (eg 'bart.jpg') from calling an async method?

thanks for your help,

Anthony

3
  • Not just a duplicate of How do I return the response from an asynchronous call, as what needs doing here is completely restructuring the component. (That said, there may well be a React-specific duplicate we can point to...) Commented Jul 3, 2020 at 9:07
  • async infront of a function simply means: this function returns an promise. so you need to handle it like an promise Commented Jul 3, 2020 at 9:08
  • Possible duplicate of stackoverflow.com/questions/51741828/… ? Commented Jul 3, 2020 at 9:12

1 Answer 1

2

Your anonymous async function in your JSX still returns a promise, just like the one you're calling. You need to fundamentally restructure your React components. Either:

  1. The component where this is being done has to be able to render when it doesn't have the result from getAssetByIdAsync yet (perhaps some "loading" placeholder), or

  2. That component shouldn't be rendered at all until that result is available, which means doing the call to getAssetByIdAsync in the parent component instead of this one.

You need to do that in order to allow time for the asynchronous operation to complete. Within whatever component is doing it, you would use .then and .catch on the call to getAssetByIdAsync in order to handle the fulfillment or rejection of the promise it returns.

Sign up to request clarification or add additional context in comments.

1 Comment

Crowler, thanks man, your suggestion helped me find the solution. I passed the renderMasterThumb method as prop to a child component. Then in the child component I render the renderMasterThumb method in the useEffect hook and set the path to a useState hook. This works!

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.