5

I'm struggling to get the actual result data from an http fetch in js. I can do it using XMLHttpRequest, but I'd much rather use fetching. I've been trying to get the results from a fetch request like this: fetch('https://api.website.net/?);

I know that you need to assign a then function but nothing I have tried has worked I keep getting more promise objects and no results. I understand vaguely that you need to assign a .then function for once it resolves but I really cannot figure out how to do that.

(This is in browser js not node)

2
  • 1
    There are thousands (millions?) of examples of promises generally and fetch specifically, without a minimal reproducible example it's hard to say what your specific problem is. If you're in a non-browser environment you will need to polyfill fetch. Commented Apr 24, 2021 at 22:39
  • 1
    lol oh come on really? you can find multiple tutorials on promise and fetch. It is better the read about promise in javascript than to just get a simple answer to your question Commented Apr 24, 2021 at 22:43

3 Answers 3

13

I think that you're getting confused with promises. The fetch function returns a promise and not the data.

I recommend that you read this modern tutorial: https://javascript.info/fetch

This is a very trivial function that gets the url and returns the response data in json:

async function callApi(url) {
  const response = await fetch(url);
  const data = await response.json();

  return data;
}

let data = await callApi('https://api.website.net/?');
// do whatever you want with the data

When dealing with primises there are 2 syntaxes, the old .then() and the new async/await. Using async/await is better, in general, so I recommend using the async/await syntax. With .then() it would look like this:

// Not recommended alternative

fetch('https://api.website.net/?')
  .then(response => response.json())
  .then(data => {
    // do whatever you want with the data
  });
Sign up to request clarification or add additional context in comments.

3 Comments

Your second part of the post is misleading. async/await is just a sugarcoat around original promises. .then is part of the original promise' synthax.
Why is the second not recommended? It works very well and is much easier to understand
When you want to split the async calls into functions, the new syntax is way clearer. When looking at just a fetch if may seem simpler, but when handling multiple promises or having many functions async/await shines. I personally prefer less indentation, that's another benefit.
1

Try this:

fetch(....)
    .then(response => response.json())
    .then(data => /* use data */);

1 Comment

you still have to wait for the promise to complete.
-1

Try this approach:

Calling a function in your code.

document.addEventListener("click", async function(e) {
        if (e.target) {
            if (Boolean(e.target.closest('span')?.classList.contains('addProduct'))) {
                e.preventDefault();
                if ('disabled' in e.target) e.target.disabled = true;
                productId = parseInt(e.target.closest('tr')?.getAttribute('id').replace('product-', '')) || 0;

                let form = new FormData();
                form.append('productId', productId);
                let result = await callApi('url-here', form);
                console.log(result);

                if ('disabled' in e.target) e.target.disabled = false;
            }
        }
    });

Wrapper function (needed for processing Promise)

async function callApi(url, form, method = 'POST', type = 'json') { // text, json, blob, formData, arrayBuffer
        try {
            return await callApiSafe(url, form, method, type);
        } catch (error) {
            console.error('Error in callApiSafe:', error);
            return null;
        }
    }

Data acquisition function

async function callApiSafe(url, form, method, type) {
        try {
            const response = await fetch(url, {
                method: method,
                cache: "no-store",
                headers: { "X-Requested-With": "XMLHttpRequest" },
                body: form
            });

            if (!response.ok) {
                if (response.status === 404) throw new Error('404, Not found');
                if (response.status === 500) throw new Error('500, Internal server error');
                throw new Error(`HTTP error: ${response.status}`);
            }

            switch (type) {
                case 'text':
                    return await response.text();
                case 'json':
                    return await response.json();
                case 'blob':
                    return await response.blob();
                case 'formData':
                    return await response.formData();
                case 'arrayBuffer':
                    return await response.arrayBuffer();
                default:
                    throw new Error('Unsupported response type');
            }
        } catch (error) {
            console.error('Request failed:', error);
            throw error;
        }
    }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.