简体   繁体   English

我的解决方案有意义吗? 处理承诺,超时,尝试/捕获

[英]Does my solution make sense? Working with promises, timeouts, try/catch

I would like to find a solution where there are two promises. 我想找到一个有两个承诺的解决方案。 The first promise must complete. 第一个承诺必须完成。 The second promise doesn't necessarily have to complete, but the user should not wait for a specific amount of time before a redirect occurs. 第二个承诺不一定必须完成,但是用户不应在重定向发生之前等待特定的时间。

I've tried to create the solution and, since I'm new, not sure how to test this code or see if it works. 我尝试创建解决方案,并且由于是新手,所以不确定如何测试此代码或查看其是否有效。 Really would like to see others opinion on why this code is good or bad and would love to improve. 真的很希望看到其他人对此代码的优缺点感到满意,并希望进行改进。

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

the apiPromise function is used to try and fetch a URL. apiPromise函数用于尝试获取URL。 It resolves if successful but then a catch statement rejects it with a new Error object 它解析是否成功,但是catch语句使用新的Error对象拒绝它

the promiseTimeout function is use to create a race condition against a given promise and the timeout promiseTimeout函数用于针对给定的promise和超时创建竞争条件

the setup function is just like a react componentDidMount or just to initiate the code. setup功能就像一个react componentDidMount一样,或者只是用来初始化代码。

In summation I'm unsure if: 1) I wrote the apiPromise correctly with a proper try and catch. 总之,我不确定是否:1)我通过适当的尝试和捕获正确地编写了apiPromise Does this make sense? 这有意义吗? 2) Will my promise.all work as expected where IF the second promise does indeed timeout, the user is redirected? 2)如果第二个诺言确实超时了,并且用户被重定向了,我的诺言是否会按预期工作?

Promise.all() always waits for each promise to return something and if one fails, it will not wait for others to finish, but will throw an error. Promise.all()总是等待每个诺言返回某些内容,如果一个失败,它不会等待其他诺言完成,而是会引发错误。

What I would do is, set the timeout into the the function that handles fetch() and then destroy it if the fetch finishes in time. 我要做的是,将超时设置为处理fetch()的函数,然后在获取及时完成后销毁它。 Otherwise the redirection will forward the user to where ever. 否则,重定向会将用户转发到任何地方。 Also in cases the fetch() does finish in time but throws an error, you might want to forward user to a different url, hence the redirect()-function. 同样,在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 } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM