2017-12-29 33 views
0

私はfetchを使ってサーバーからデータを取得しています。サーバーが応答しなかった場合のフェッチのタイムアウトを設定できません。フェッチのタイムアウト - ネイティブ応答

私のグローバルなFetchDataクラス

fetchGetResp(url, token) { 
    return fetch(url, { 
     method: "GET", 
     headers: { 
      'Accept': 'application/json', 
      'Content-Type': 'application/json', 
     } 
    }) 
    // .then(ApiUtils.checkStatus) 
    .then(response => 
     response.json() 
    ) 
    .then(responseJson => { 
     return responseJson 
    }) 
    .catch(error => { 
     // console.log(error.headers._bodyText.status); 
     console.log('touching undefined catch'); 
     return undefined; 
    }); 
} 

私はなFetchData

let resp = fetchData.fetchGetResp(restUrl, userToken); 
resp.then(responseJson => { 
    // console.log(res); 
    if (responseJson != '' && responseJson != undefined) { 

    } 
    else { 
     console.log(responseJson); 
     try { 
     } 
     catch (error) { 
      alert(error.message); 
      console.log(error + 'from js file'); 
     } 
    } 

    //Some if statement 
    else { 
     alert('Unable to Process.please try again'); 
    } 
}) 
.catch(error => { 
    alert(error.message + "Please try again after sometime"); 
}); 

にアクセスするよどこJavascriptのクラス私上記のアプローチに基づいてタイムアウトを実装する方法をお聞かせください。

+0

現時点でタイムアウトをサポートしていません取得、私はあなたが使用することをお勧めします[axios](https://www.npmjs.com/package/axios)または[api-sauce](https://github.com/infinitered/apisauce) –

答えて

0

フェッチは現在(2014年12月29日)のタイムアウトオプションをサポートしていませんが、現在議論中の(discussion link)です。

しかし、これらのドキュメントに従って、独自のラッパーを定義する方法があります。あなたのケースではそのためlink1link2

function timeout(ms, promise) { 
    return new Promise(function(resolve, reject) { 
     setTimeout(function() { 
      reject(new Error("timeout")) 
     }, ms); 
     promise.then(resolve, reject) 
    }) 
}; 

timeout(1000, fetchData.fetchGetResp(restUrl, userToken)).then(responseJson => { 
    // console.log(res); 
    if (responseJson != '' && responseJson != undefined) { 

    }else { 
     console.log(responseJson); 
     try { 
     } catch (error) { 
      alert(error.message); 
      console.log(error + 'from js file'); 
     } 

    } 

}).catch(error => { 
    alert(error.message + "Please try again after sometime"); 
}); 
関連する問題