【问题标题】:ApolloClient timeout best optionApolloClient 超时最佳选择
【发布时间】:2017-04-11 18:49:15
【问题描述】:

我想出了用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')
});

有没有更好的方法可以用更少和更简单的代码实现相同的结果?

【问题讨论】:

    标签: javascript graphql apollostack


    【解决方案1】:

    原来,你可以重写方法:

    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;
      });
    }
    

    【讨论】:

      猜你喜欢
      • 2018-05-05
      • 2021-11-24
      • 2012-10-24
      • 2013-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-01
      相关资源
      最近更新 更多