-1

I'm currently trying to grab data in TypeScript using axios.get:

        try {
            const resp = axios.get("http://localhost:8080/getdata").then(response => response.data)
            return resp
            // return "<img src=\"" + resp + "\"></div>"
        } catch (exception) {
            console.log("Error")
        }

When I return resp, it returns the correct response (e.g. data:image/png;base64 ...), however, when I return it as <img src="resp"> it returns [object Promise] instead. Any ideas?

  • Does this answer your question? [Why is my asynchronous function returning Promise { } instead of a value?](https://stackoverflow.com/questions/38884522/why-is-my-asynchronous-function-returning-promise-pending-instead-of-a-val) – Ivar Jun 17 '21 at 07:06
  • Unfortunately not, have tried already. – user15882500 Jun 17 '21 at 07:09
  • 1
    Try with async/await :) – WSD Jun 17 '21 at 07:12
  • Tried what exactly? That post explains perfectly what is going on. There isn't much more we can tell you. You can't directly return a value from a asynchronous operation. You can either return the Promise and wait for it to resolve in the calling function, or you can take some action in the `.then()` callback. – Ivar Jun 17 '21 at 07:13

2 Answers2

0

Give it a try to the async/await approach.

async function yourMethodName() {
try {
const response = await axios.get("http://localhost:8080/getdata");
return `<img src="${response.data}">`;

} catch(e) {
console.log(e);
}

}

Alternatively, you can simply use the callback approach.

axios.get("http://localhost:8080/getdata").then((response) => { console.log(response); });

Your logic needs to run inside the callback.
If you want to learn more about Promises this will help. It uses the fetch API instead of AXIOS, but it's similar.

WSD
  • 3,243
  • 26
  • 38
-1

[object Promise] is what gets returned when the program hasnt finished what it is doing yet. to get data out of this you need to resolve the promise.

try replacing the code in your try statement with this:

const resp = axios.get("http://localhost:8080/getdata).then(response => response.data");
var promise = Promise.resolve(resp);

promise.then(function(value){

    return `<img src=" ${value} "></div>`;

});
KCGD
  • 675
  • 6
  • 10
  • 1
    `axios.get()` already returns a Promise. What's the point of `Promise.resolve(resp)`? (Not to mention that this has been answered thousands of times on Stack Overflow. [It doesn't really need yet another answer](https://stackoverflow.com/help/duplicates).) – Ivar Jun 17 '21 at 07:16