fetch 返回的是一个 Promise 对象, 每个 promise 对象最后会有 resolve 或 reject 两种状态, then 方法是 promise 对象的方法, then 方法返回的也是一个 promise 对象,所以 then 可以连着写。
get = (url) =>
fetch(url, {
method: 'GET',
}).then(resp => Promise.all([resp.ok, resp.status,resp.json()])
).then(([ok, status, json]) => {
if (ok) {
return json;
} else {
this.handleError(status, json.error);
throw new Error(json.error);
}
}).catch(error => {
throw error;
});
post = (url, body) => this._request(url, body, 'POST');
put = (url, body) => this._request(url, body, 'PUT');
_delete = (url, body) => this._request(url, body, 'DELETE');
_request = (url, body, method) =>
fetch(url, {
method: method,
body: JSON.stringify(body)
}).then(resp => {
return Promise.all([resp.ok, resp.status, resp.json()]);
}).then(([ok, status, json]) => {
if (ok) {
return json;
} else {
this.handleError(status, json.error);
throw new Error(json.error);
}
}).catch(error => {
throw error;
});
fetch 对所有的 response code 包括 200X 300X 400X 500X 等返回的都是 resolve 状态, 只有抛异常时才会走到 catch 里面, 所以我们希望把 非200X 请求作为 reject 状态区分出来, 在 REST API 中 300X 400X 500X 的状态码通常意外着错误,服务端通常还会返回一个 errorCode 和 errorMessage 来表示错误原因。
所以很简单直接通过 response code 区分出来就行了 : if (response.status >= 200 && response.code < 300)。 fetch 的 Response 对象的 ok 属性就是干这个事情的
if (response.ok) {
return json;
} else {
throw new Error(json.error);
}
ok 时直接返回 json, 其它情况抛出异常, 所有的异常放到 catch 里面去处理, 抛异常时当前 promise 也是 reject 状态,我们应该把这个异常继续抛出这样外界调用时就可以用 catch 进行异常处理了。
这里我们用了 Promise.all([resp.ok, resp.status,resp.json()]) 把 ok status response.json() 都放到一个 then 里面去处理, 因为非 ok 时我们也要从 response.json() 中拿错误信息。
注意 response.json() 返回的也是一个 Promise 对象
Promise.all 可以组合多个 Promise ,只有所有的 promise 都 resolve 时其结果才会是 resolve, 只要有一个 reject 结果就是 reject 状态。 如果数组中元素不是 promise 对象会先转为 promise 对象。
注意在 catch 里面抛出异常, 这个 promise 就是 reject 状态, 在外面可以这样使用
getUsers() {
return get('/api/users').then(json => {
return json;
}).catch(error=>{
// 这里处理错误
});
}
注意我们每次都返回了一个 Promise 对象 (fetch 本身返回的就是 Promise) 所以使用的时候可以级联写
我们调用 getUsers 的时候就可以这样写
getUsers.then(json => {
// 处理数据
return json;
}).catch(error=>{
});
每一个方法都返回 Promise 对象, 我们可以一层一层的根据自己的实际情况处理数据。
网友评论