fetch 超時處理

You can implement your own timeout wrapper for Promises:promise

// Rough implementation. Untested. function timeout(ms, promise) { return new Promise(function(resolve, reject) { setTimeout(function() { reject(new Error("timeout")) }, ms) promise.then(resolve, reject) }) }app

timeout(1000, fetch('/hello')).then(function(response) { // process response }).catch(function(error) { // might be a timeout error }) The timeout() function will wrap any promise and ensure that it's at least rejected within ms milliseconds. If the fetch succeeds to resolve earlier than that, then the request will be successful.fetch

Note that this is not a connection timeout. This is a response timeout. Due to technical restrictions we can't implement a connection timeout. Also note that with the above implementation, even if the timeout happens, the original request won't be aborted because we don't have an API to abort fetch requests. Instead, the request will complete in the background but its response will get discarded.this