将while循环中的async await转换为promises

4

我不知道如何将while循环中的async await功能转换为基于promise的实现。

以下是使用async await的示例代码:

https://repl.it/repls/IdealisticPepperyCoding

需要注意的是,代码中保留了HTML标签。

var dependency = false;

function checkDependency() {
  return new Promise(resolve => {
    setTimeout(() => {
      dependency = true;
      return resolve();
    }, 1000)
  });
}

async function isReady() {
    while(!dependency) {
      console.log('not loaded');
      await checkDependency();
    }
    console.log('loaded')
}

isReady();


1
你尝试过什么没有成功吗? - Ry-
移除了 async/await 并尝试使用 checkDependency().then()。 - Zack Lucky
1
Uh, async-await 基于 Promise 的,所以我不确定你在问什么?代码是否有效,有什么问题? - Bergi
顺便提一下,你的 checkDependency 函数应该使用布尔值解决返回的 Promise,而不是改变某个全局的 dependency 变量。 - Bergi
我猜这远非“实际代码”,因为有大约100种更好的编写方式:p - Jaromanda X
@ZackLucky,看起来你有一个用于 false/true 值的流。你可以考虑使用 RxJS 流扩展 - AlexMelw
3个回答

6
如果我理解正确的话,您想要使用不带async函数的Promise而不是带async函数的Promise,并且示例中的checkDependency在某些情况下可能实际上并不会将dependency = true设置,因此您想要“循环”。等效功能可能如下所示,其中您可以“递归”调用check函数。虽然调用是在异步回调中完成的,但它实际上不会递归并导致堆栈溢出:
var dependency = false;

function checkDependency() {
  return new Promise(resolve => {
    setTimeout(() => {
      dependency = true;
      return resolve();
    }, 1000)
  });
}

function isReady() {
  if (!dependency) {
    return checkDependency().then(isReady);
  }

  return Promise.resolve(true);
}

isReady().then(() => {
  console.log('loaded')
});

4

您不需要使用while循环。

checkDependency().then(() => { console.log('loaded');});


我的错,承诺中的 dependency = true 并不总是正确的,这种情况下需要再次检查。 - Zack Lucky
1
@ZackLucky,看起来你有一个用于 false/true 值的流。你可以考虑使用 RxJS 流扩展 - AlexMelw

0
  • 你不需要返回recolve(),只需调用它。
  • 在函数isReady内调用函数then

function checkDependency() {
  return new Promise(resolve => {
    setTimeout(resolve, 1000);
  });
}

function isReady() {
  console.log('not loaded');
  checkDependency().then(() => {
    console.log('loaded')
  });
}

isReady();


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接