[英]I try to make a while loop in javascript. I have example of what i'm trying to do in body
const condition = true;
while (condition) condition = checkCondition();
function checkCondition(){
(async () => {
if (await page.$('condition') !== null){ // condition met
return true;
} else { // condition not met
return false;
}
})();
}
I'm not sure if I am doing it right.我不确定我是否做得对。 Please can someone show me the right way.
请有人告诉我正确的方法。
prime's answer will bring you closer and provides some useful material to read up on. prime 的回答将使您更接近并提供一些有用的材料来阅读。 I though I would build on it a bit by fixing a couple issues and adding some more explanation.
我想我会通过修复几个问题并添加更多解释来建立它。
Below is a working demonstration of your code以下是您的代码的工作演示
(async function() { let condition = true; while (condition) condition = await checkCondition(); })() async function checkCondition() { console.log('checkCondition was called'); if (await someAsyncLogic() !== null){ // condition met return true; } else { // condition not met return false; } } async function someAsyncLogic() { return Math.random() > 0.2 ? true : null; }
Your code effectively had the following:您的代码有效地具有以下内容:
function checkCondition(){
(async () => {
// do some logic
return true/false
})();
}
What's wrong here is that your return true/false is just going to make your inner IIFE (async () => ...)()
provide a promise that resolve to true/false.这里的错误在于您的返回 true/false 只会让您的内部 IIFE
(async () => ...)()
提供一个解析为 true/false 的承诺。 You could even store that value in a variable if you cared.如果您愿意,您甚至可以将该值存储在一个变量中。
function checkCondition(){
const theResult = (async () => {
// do some logic
return true/false
})();
console.log(theResult) // <-- [object Promise]
console.log(await theResult) // <-- true/false
}
But, as we can see, checkCondition itself doesn't return anything .但是,正如我们所看到的, checkCondition 本身不返回任何内容。 Only the inner function inside does.
只有内部的内部函数可以。 You would have to return theResult to do so - but in order to do that, you would need to declare checkCondition as an async function, at which point, there's no need for your async IIFE anymore, which is why that example takes it out.
您必须返回 theResult 才能这样做 - 但为了做到这一点,您需要将 checkCondition 声明为异步函数,此时,不再需要您的异步 IIFE,这就是该示例删除它的原因。
If checkCondition is async, then the code calling it has to use await, and has to be withing an async context (like an async IIFE, or a normal async function).如果 checkCondition 是异步的,那么调用它的代码必须使用 await,并且必须使用异步上下文(如异步 IIFE 或普通的异步函数)。
For more detail, please check: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function更多详情,请查看: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
const condition = true;
while (condition) condition = checkCondition();
async function checkCondition() {
if (await page.$('condition') !== null){ // condition met
return true;
} else { // condition not met
return false;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.