我如何在While循环中使用访存 [英] How can I use fetch in while loop

查看:28
本文介绍了我如何在While循环中使用访存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码是这样的:

var trueOrFalse = true;
while(trueOrFalse){
    fetch('some/address').then(){
        if(someCondition){
            trueOrFalse = false;
        }
    }
}

但是我不能发出获取请求.似乎while循环正在计划将许多访存操作移入下一个刻度.但是千万不要跳到下一个刻度.我该如何解决这个问题?

But I can not issue the fetch request. It seems like while loop is schedule many fetches into next tick. But never skip to next tick. How can I solve the problem?

推荐答案

while(true)创建一个无限循环,该循环将尝试调用 fetch 无数次在一个单个刻度" 中.由于它永远不会完成发出新的 fetch 调用,因此永远不会到达下一个刻度.

while(true) creates an infinite loop, which will attempt to call fetch infinitely many times within a single "tick". Since it never finishes issuing new fetch calls, it never gets to the next tick.

此功能占用大量CPU,可能会锁定整个页面.

This function is very CPU-intensive and will probably lock up the entire page.

有什么解决方案?

您可能要尝试做的是继续获取​​,直到结果满足某些条件为止.您可以通过检查 then 回调中的条件并重新发出 false (如果为 false :

What you are probably trying to do is keep fetching until the result satisfies some condition. You can achieve that by checking the condition in the then callback, and re-issuing the fetch if it is false:

var resultFound = false;

var fetchNow = function() {
  fetch('some/address').then(function() {
    if(someCondition) {
      resultFound = true;
    }
    else {
      fetchNow();
    }
  });
}

fetchNow();

这样,而不是

fetch!
fetch!
fetch!
fetch!
...

...行为将会发生

fetch!
  wait for response
  check condition
if false, fetch!
  wait for response
  check condition
if true, stop.

...这可能是您所期望的.

...which is probably what you expected.

这篇关于我如何在While循环中使用访存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆