gpt4 book ai didi

javascript - while循环中的函数只执行一次

转载 作者:行者123 更新时间:2023-11-28 18:55:40 25 4
gpt4 key购买 nike

我是 javascript 的初学者,我试图弄清楚为什么我的 while 循环实际上不会循环多次,即使条件总是满足。

我有一个发送 API 请求的函数:

var get_status = function(trid, count) {
console.log(count);
var req = {
method: 'GET',
url: 'theUrlHere',
headers: {'headers'}
}
$http(req).success(function(data) {
if (data.transaction_status != 'Pending') {
// do something with the data
console.log('true');
return true;
}
else {
console.log('False');
return false;
}
}).error(function(data) {
// show an error popup
console.log('true');
return true;
})
}
};

我想调用这个函数直到它返回true,所以我这样调用它:

var count = 0;
while (get_status(id, count) === false) {
count += 1;
}

只是添加了 count 变量来查看它循环了多少次,即使控制台中显示“False”,它仍保持为 0。

我在这里有什么误解吗?

编辑我明白为什么这不起作用。我的目的是只要交易状态处于挂起状态就显示 iframe。我想过不断发送请求,直到交易状态变为“待处理”以外的状态,但我知道还有更优化的方法。

最佳答案

您的 get_status() 函数不返回值。因此,它的返回值是 undefined 这是错误的,因此您的 while() 循环在第一次迭代后停止。

代码中的 return 语句位于回调内部,与 get_status() 的返回值无关。

<小时/>

您尝试做的事情通常不是一个好的设计。看来您想要一遍又一遍地运行给定的 Ajax 调用,直到获得所需的答案。这可能会影响目标服务器。

如果您描述了您真正想要解决的问题,我们可以帮助您想出更好的方法来做到这一点。最坏的情况是,您可以在请求之间设置一定的时间延迟来轮询服务器。

如果您想经常进行轮询,您可以这样做:

function get_status(trid, count) {
var req = {
method: 'GET',
url: 'theUrlHere',
headers: {'headers'}
}
return $http(req).then(function(data) {
return data.transaction_status;
});
}

function poll_status(callback) {
function next() {
get_status(...).then(function(status) {
if (status === "Pending") {
// poll once every two seconds
setTimeout(next, 2000);
} else {
// status is no longer pending, so call the callback and pass it the status
callback(status);
}
}, function(err) {
callback(err);
});
}
next();
}


poll_status(function(result) {
// done polling here, status no longer Pending
});

关于javascript - while循环中的函数只执行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33666109/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com