ApolloClient 超时最佳选择
ApolloClient timeout best option
我想到了这种用ApolloClient
进行网络操作的方法,但问题是代码看起来很难看,而且很难阅读,考虑到我必须写几十个这样的查询,它变得很累并且无法维护。
我没有在 Apollo 文档或配置超时的实际代码中找到任何内容。
let query = gql`
query ... {
}`;
let x = 0;
let timer = setTimeout(() => {
if (x === 0) {
console.log('error');
}
x = 1;
}, 3000);
ApolloClient.query({ query }).then(({data}) => {
clearTimeout(timer);
if (x === 0) {
if (data.result) {
console.log(data.result)
} else {
console.log('error');
}
}
}).catch((error) => {
clearTimeout(timer);
console.log('error')
});
有没有更好的方法用更少更简单的代码实现相同的结果?
事实证明,您可以重写该方法:
export async function query(request) {
const options = {...this._opts};
return new Promise((resolve, reject) => {
setTimeout(() => reject('Network timed out'), 1e4); // 10 sec
return this.applyMiddlewares({
request,
options
}).then((rao) => {
return this.fetchFromRemoteEndpoint.call(this, rao);
}).then(response => this.applyAfterwares({
response: response,
options
})).then(({response}) => (response).json()).then((payload) => {
resolve(payload);
}).catch((e) => {
reject(e);
});
}).catch((e) => {
console.log(e);
return null;
});
}
我想到了这种用ApolloClient
进行网络操作的方法,但问题是代码看起来很难看,而且很难阅读,考虑到我必须写几十个这样的查询,它变得很累并且无法维护。
我没有在 Apollo 文档或配置超时的实际代码中找到任何内容。
let query = gql`
query ... {
}`;
let x = 0;
let timer = setTimeout(() => {
if (x === 0) {
console.log('error');
}
x = 1;
}, 3000);
ApolloClient.query({ query }).then(({data}) => {
clearTimeout(timer);
if (x === 0) {
if (data.result) {
console.log(data.result)
} else {
console.log('error');
}
}
}).catch((error) => {
clearTimeout(timer);
console.log('error')
});
有没有更好的方法用更少更简单的代码实现相同的结果?
事实证明,您可以重写该方法:
export async function query(request) {
const options = {...this._opts};
return new Promise((resolve, reject) => {
setTimeout(() => reject('Network timed out'), 1e4); // 10 sec
return this.applyMiddlewares({
request,
options
}).then((rao) => {
return this.fetchFromRemoteEndpoint.call(this, rao);
}).then(response => this.applyAfterwares({
response: response,
options
})).then(({response}) => (response).json()).then((payload) => {
resolve(payload);
}).catch((e) => {
reject(e);
});
}).catch((e) => {
console.log(e);
return null;
});
}