Skip to content
Advertisement

fetch response.text() returns pending promise

I test the fetch API with jsonplaceholder URL, but my function returns “Promise State: Pending”, and I don’t understand why :

JavaScript

I think the problem is because of asynchronous/synchronous methods?

Advertisement

Answer

I think the problem become asynchrone/synchrone method ?

Yes. You’ve (mostly) correctly consumed the original fetch() promise, but text() also returns a promise. So:

JavaScript

JavaScript

At #1 above, we respond to the successful resolution of the fetch() promise by starting the process of reading the body text, returning the promise from text().

At #2 above, we respond to the successful resolution of text()‘s promise by using the resulting text (a string containing JSON).

At #3 above, we handle an error from either the original fetch() or the text() promise by doing something with it.

Always be sure to handle promise rejections. If you don’t, they’re unlike unhandled exceptions. They’re reported to the console, and some environments (like recent versions of Node) terminate on unhandled rejections.


Since you’re requesting JSON, you might want to use json() rather than text() so you both read and parse it:

JavaScript

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement