【发布时间】:2019-11-01 16:18:12
【问题描述】:
我在 React-Native 中有一个登录页面。如果我有 Internet 连接,它可以正常工作,但我现在想处理 Internet(或服务器)关闭的情况。我想这样做的方法是使用超时:应用程序应该尝试连接,如果五秒钟内没有成功,我想打印一条错误消息。
我使用以下代码完成了这项工作,取自here:
export function timeout(
promise,
message = 'Request timeout',
timeout = DEFAULT_TIMEOUT,
) {
return new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
console.log('timeout called');
reject(new Error(message));
}, timeout);
promise.then(
response => {
clearTimeout(timeoutId);
resolve(response);
},
err => {
console.log('timeout NOT called');
clearTimeout(timeoutId);
reject(err);
},
);
});
}
从登录页面,我们这样称呼它:
response = await timeout(
getAccessToken(this.state.username, this.state.password),
'Unable to connect to the server.',
);
其中getAccessToken 是fetch 的异步包装器。它在第一次登录尝试时工作正常(互联网关闭)。它等待五秒钟 (DEFAULT_TIMEOUT),然后打印“无法连接到服务器”错误消息。问题是,如果我再次单击登录按钮,该应用程序不会等待五秒钟并打印一个通用的“网络错误”。我们可以在logkitty看到问题:
[12:08:44] I | ReactNativeJS ▶︎ timeout called (first click)
[12:08:49] I | ReactNativeJS ▶︎ timeout NOT called (second click)
我不明白为什么在第二次登录尝试时未触发超时并且timeout 自动失败。有什么问题,我该如何解决?
【问题讨论】:
-
getAccessToken 函数是 Promise??
-
@hongdevelop 是的,它返回一个承诺
标签: javascript react-native timeout fetch-api