2017-08-28 8 views
-1

私はmern.ioスタックから来た次の関数を持っています。フェッチを使用して、リジェクトを正しく処理する方法

export default function callApi(endpoint, method = 'get', body) { 
    return fetch(`${API_URL}/${endpoint}`, { 
    headers: { 'content-type': 'application/json' }, 
    method, 
    body: JSON.stringify(body), 
    }) 
    .then(response => response.json().then(json => ({ json, response }))) 
    .then(({ json, response }) => { 
    if (!response.ok) { 
     return Promise.reject(json); 
    } 
    return json; 
    }) 
    .then(
    response => response, 
    error => error 
); 
} 

私は機能応答が201または422がどのように422適切な方法を扱うことができるのどちらかになります

callApi('auth/register', 'post', { 
     username, 
     password, 
}).then(function(res) { 
    // do stuff 
}); 

次のように呼び出しますか?ユーザー名が既に存在する場合、422が発生します。

callApi('auth/register', 'post', { 
     username, 
     password, 
}).then(function(res) { 
    if (res.error) { 

    } else { 
    } 
}); 
+0

それをdoesntのエラーを投げ、ここにレポのコードがあります:https://github.com/Hashnode/mern-starter/blob/master/client/util/apiCaller.js – Jose

+1

問題のウィットhは 'callApi'の最後の' then'ですが、失敗した約束をIMOがばかげている解決済みのものに変えます。それは完全に省略する必要があります – Phil

答えて

1

callApiがPromiseオブジェクトを返すと仮定:詳細については

callApi('auth/register', 'post', { 
     username, 
     password, 
}).then(function(res) { 
    // res 
}).catch(function(err) { 
    // handle err 
}); 

を:

は、私は、次のような最初のすべてのロジック入れくださいhttps://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise

+0

それはhttps://github.com/matthew-andrews/isomorphic-fetchを使用しておりcatchメソッドには決して行きません。 – Jose

+0

@Joseフルフィルメントハンドラーに新しいエラーを投げることができます。 – hisener

関連する問題