最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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();
};
发布评论

评论列表(0)

  1. 暂无评论