javascript - fetch api throws uncaught in promise error - Stack Overflow

I have a wrapper function for the fetch api to fetch different endpoints to my api but somehow it keeps

I have a wrapper function for the fetch api to fetch different endpoints to my api but somehow it keeps plaining that there is unhandled rejection TypeError: Cannot read property 'catch' of undefined

const apiRequest = (url) => {
    return fetch()
    .then(async resp =>{
        const json = await resp.json()
        if(json.status == "success") return json
        return Promise.reject('err')
    })
    .catch(err => {
         return Promise.reject(err)
     })   
}

calling the function like:

apiRequest('/test')
.then(data => console.log(data))
 .catch(err => console.log(err))

what am I doing wrong?

I have a wrapper function for the fetch api to fetch different endpoints to my api but somehow it keeps plaining that there is unhandled rejection TypeError: Cannot read property 'catch' of undefined

const apiRequest = (url) => {
    return fetch()
    .then(async resp =>{
        const json = await resp.json()
        if(json.status == "success") return json
        return Promise.reject('err')
    })
    .catch(err => {
         return Promise.reject(err)
     })   
}

calling the function like:

apiRequest('/test')
.then(data => console.log(data))
 .catch(err => console.log(err))

what am I doing wrong?

Share Improve this question edited Jan 5, 2020 at 17:47 hmaxx asked Jan 5, 2020 at 17:43 hmaxxhmaxx 6672 gold badges9 silver badges19 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

Note: When this answer was posted, the question didn't have the return. The OP added it afterward, claiming it was in their original code. But they also accepted the answer, so something below must have helped... :-)


apiRequest needs to return the promise chain. Right now, it doesn't, so calling it returns undefined.

const apiRequest = (url) => {
    return fetch(url) // *** Note: Added `url` here
//  ^−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
    .then(async resp =>{
        const json = await resp.json()
        if(json.status == "success") return json
        return Promise.reject('err')
    })
    .catch(err => {
         return Promise.reject(err)
    })
}

But, three things:

  1. There's no point whatsoever to that catch handler; and

  2. You need to check for response success before calling json; and

  3. There's no reason for that then handler to be an async function.

Instead:

const apiRequest = (url) => {
    return fetch(url) // *** Note: Added `url` here
    .then(resp => {
        if (!resp.ok) {
            throw new Error("HTTP status " + resp.status);
        }
        return resp.json();
    })   
};

(I've also added some missing semicolons there, but if you prefer to rely on ASI, just leave them off.)

If the fetch promise is rejected, that rejection will be carried through to the promise from apiRequest for the caller to handle. If the fetch promise is fulfilled but resp.ok is false (because there was an HTTP level error like a 404 or 500), the promise from apiRequest will be rejected with the error thrown in the then handler. If those things work but the json call fails, the promise from apiRequest will be rejected with the error from json. Otherwise, the promise from apiRequest will be fulfilled with the parsed data.

It can also be a concise form arrow function if you prefer:

const apiRequest = (url) => fetch(url).then(resp => { // *** Note: Added `url` to `fetch` call
    if (!resp.ok) {
        throw new Error("HTTP status " + resp.status);
    }
    return resp.json();
});   

Your original code used an async function in then. If you can ues async functions in your environment, you may prefer to make apiRequest an async function:

const apiRequest = async (url) => {
    const resp = await fetch(url); // *** Note: Added `url` here
    if (!resp.ok) {
        throw new Error("HTTP status " + resp.status);
    }
    return resp.json();
};

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745432021a4627434.html

相关推荐

  • javascript - fetch api throws uncaught in promise error - Stack Overflow

    I have a wrapper function for the fetch api to fetch different endpoints to my api but somehow it keeps

    5小时前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信