我的解决方案有意义吗?使用承诺、超时、尝试/捕获



我想找到一个有两个承诺的解决方案。 第一个承诺必须完成。 第二个承诺不一定必须完成,但用户不应在重定向发生之前等待特定的时间。

我尝试创建解决方案,但由于我是新手,不确定如何测试此代码或查看它是否有效。 真的很想看到其他人对为什么这段代码是好是坏的看法,并希望改进。

async function apiPromise(url) {
try {
const response = await fetch(url);
const json = response.json(); 
return {json}
} catch (error) {
console.error(error);
}
}
// promise timeout wrapper race condition
function promiseTimeout(ms, promise) {
// Create a promise that rejects in <ms> milliseconds
let timeout = new Promise((resolve, reject) => {
let id = setTimeout(() => {
reject('Timed out in '+ ms + 'ms.')
}, ms)
})
// Returns a race between our timeout and the passed in promise
return Promise.race([
promise,
timeout
]).then(result => {
clearTimeout(id);
return result
})
}
// let's assume this runs, componentDidMount
function setup() {
let promises = [apiPromise('url'), timeoutPromise(5000, apiPromise('url'))]
Promise.all(promises)
.then(results => {
// do whatever with the results array
})
.catch(error=> {
console.error(error);
window.location.href= '/redirect'
})
}

apiPromise函数用于尝试获取 URL。 如果成功,它会解析,但随后 catch 语句会使用新的 Error 对象拒绝它

promiseTimeout函数用于针对给定的承诺和超时创建争用条件

setup函数就像一个反应组件DidMount或只是为了启动代码。

总而言之,我不确定是否: 1(我通过适当的尝试和捕捉正确编写了apiPromise。 这有意义吗? 2(我的promise.all是否会按预期工作,如果第二个承诺确实超时,用户将被重定向?

Promise.all(( 总是等待每个 promise 返回一些东西,如果一个失败,它不会等待其他人完成,而是会抛出一个错误。

我要做的是,将超时设置到处理 fetch(( 的函数中,然后在 fetch 及时完成时销毁它。否则,重定向会将用户转发到任何位置。此外,如果 fetch(( 确实及时完成但抛出错误,您可能希望将用户转发到不同的 url,因此使用 redirect((-函数。

async function apiPromse(url) {
const timeout = timeOut(() => redirect(url), ms);    
try {
const response = await fetch(url);
// Destroy timeout if a response is received, otherwise redirect
clearTimeout(timeout);
return await response.json();
} catch (error) {
console.log(error);
// Redirect to another url in case the fetch() fails
clearTimeout(timeout);
redirect(url);
}
}
function redirect(url) {
window.location.href(url)
}
async function setup() {
const apiResult = await this.apiPromise('url');
// Do Stuff with apiResult
}

最新更新