我尝试在 JavaScript 中创建一个 while 循环。我有一个我想在身体上做的例子

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;

        }

    })();

}

我不确定我做得是否正确。请有人告诉我正确的方法。


蝴蝶刀刀
浏览 145回答 2
2回答

偶然的你

prime 的答案将使您更接近并提供一些有用的材料供阅读。我想我会通过修复几个问题并添加更多解释来在此基础上进行一些改进。下面是您的代码的工作演示(async function() {&nbsp; let condition = true;&nbsp; while (condition) condition = await checkCondition();})()async function checkCondition() {&nbsp; console.log('checkCondition was called');&nbsp; if (await someAsyncLogic() !== null){ // condition met&nbsp; &nbsp; return true;&nbsp; } else { // condition not met&nbsp; &nbsp; return false;&nbsp; }}async function someAsyncLogic() {&nbsp; return Math.random() > 0.2 ? true : null;}您的代码实际上具有以下内容:function checkCondition(){&nbsp; &nbsp; (async () => {&nbsp; &nbsp; &nbsp; &nbsp; // do some logic&nbsp; &nbsp; &nbsp; &nbsp; return true/false&nbsp; &nbsp; })();}这里的问题是,你的 return true/false 只会让你内心的 IIFE(async () => ...)()提供一个解析为 true/false 的承诺。如果您愿意,您甚至可以将该值存储在变量中。function checkCondition(){&nbsp; &nbsp; const theResult = (async () => {&nbsp; &nbsp; &nbsp; &nbsp; // do some logic&nbsp; &nbsp; &nbsp; &nbsp; return true/false&nbsp; &nbsp; })();&nbsp; &nbsp; console.log(theResult) // <-- [object Promise]&nbsp; &nbsp; console.log(await theResult) // <-- true/false}但是,正如我们所看到的, checkCondition 本身不返回任何内容。只有里面的内部函数才可以。您必须返回 theResult 才能执行此操作 - 但为了做到这一点,您需要将 checkCondition 声明为异步函数,此时,不再需要异步 IIFE,这就是该示例将其删除的原因。如果 checkCondition 是异步的,那么调用它的代码必须使用 wait,并且必须位于异步上下文中(如 async IIFE 或普通的异步函数)。

天涯尽头无女友

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;   }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript