JS Fetch:如何 return 响应正文或错误?

JS Fetch: How to return response with body or error?

我正在努力将此代码从 ajax 移至获取。我想调用 API 和

    function getAPI(url, requestOptions) {
    return fetch(url, requestOptions).then((response) => {
        return response.json().then(json => {
            response.json = json;
            console.log(response);
            return response;
        })
        .catch(error => {
            console.error('Error:', error);
            response.error = error;
            return response;
        });
    }).catch(error => {
        console.error('Error:', error);         
        response.error = error;
        return response;
    });
}

我想你想要得到这个结果

async function getAPI(url, requestOptions) {
    let result;

    await fetch(url, requestOptions)
        .then(response => response.json())
        .then(response => result = response)
        .catch(error => console.error('Error:', error))

    return result;
}

使用:

await getAPI('https://jsonplaceholder.typicode.com/todos/1')

它 returns 响应。

// 已编辑,添加状态

async function getAPI(url, requestOptions) {
    let result;

    await fetch(url, requestOptions)
        .then(response => response.json())
        .then(response => result = { status: 'success', response })
        .catch(error => result = { status: 'error', error })

    return result;
}