首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在反应中每一秒发送请求

在反应中每一秒发送请求
EN

Stack Overflow用户
提问于 2022-09-02 12:40:39
回答 1查看 40关注 0票数 0

在响应res.readyToShow ===真之前,我如何每秒钟进行一次提取请求。如果res.status为真,则停止请求。

我希望每秒钟发送一个请求,以验证readyToShow是否为真。我不能使用套接字或网络钩子。

代码语言:javascript
复制
 test = (ossUrn, md5Checksum) => setTimeout (() => {
    fetch(
      `google/isReadyToShow`,{
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        urn: ossUrn,
        md5Checksum: md5Checksum,
      }),
    })
    .then((response) => {
      response.json().then((res) => {
          console.log('response ', res);
          return (res.readyToShow)  ? 0 : this.test(ossUrn, md5Checksum);
        });
    })
      .catch((err) => {
        console.log('err ', err);
      });
  } , 2.5 * 1000);
代码语言:javascript
复制
return fetch(
          `google/translation`,
          {
            headers: {
              'X-ACCESS-TOKEN-APP' : accessTokenApp,
              'X-DRIVE-ID': e.itemData.id,
              'X-FILE-NAME': e.itemData.name,
              'X-FILE-TYPE': e.itemData.mimeType,
              'X-FILE-MD5': e.itemData.md5Checksum,
            },
          }
        )
        .then((response) => {
            console.log("google item of id clicked " + e.itemData.id);
            response.json().then((res) => {
              console.log('response ', res);
              md5Checksum = e.itemData.md5Checksum;
              ossUrn =  res.urn;
              console.log('URN ', ossUrn)
              console.log('URL', res);
              console.log('MD5', md5Checksum);
              // execute the function to check if the file is ready to be shown
              this.test(ossUrn, md5Checksum);
            })         
              .catch((err) => {
                console.log(err);
              });
        }).catch(() => { throw new Error('Data Loading Error'); });
      
    }

我尝试使用这段代码,但是我有一个错误:

代码语言:javascript
复制
TypeError: Cannot read properties of undefined (reading 'test')
EN

回答 1

Stack Overflow用户

发布于 2022-09-02 12:57:35

您可以将setInterval与一个变量或状态一起使用,该变量或状态确定间隔是否应该继续,或者如果您应该调用clearInterval,因为您已经得到了所需的结果。类似于:

代码语言:javascript
复制
function myIntervalFunction() {
   fetch(/*your fetch code*/).then(res => {
      if(res.readyToShow) {
         // setState, or change a let variable to true
      }
   })
}

const myInterval = setInterval(myIntervalFunction, 1000) // executes every 1s
// if you're doing it inside a component use state, if outside use a let that starts with false
if(myState || myLetVar === true) { // got what you wanted
  clearInterval(myInterval) // stops interval
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73582722

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档