【问题标题】:javascript async await for function before continuingjavascript async await for function 在继续之前
【发布时间】:2021-11-07 05:16:30
【问题描述】:

我有一个调用其他函数的辅助函数。我希望调用的函数在继续使用辅助函数之前完成。

目前他们都在同时改变事物。

helperDikjstras = async() => {
  //do stuff
  await this.colorVisited(visitedNodes); // I want this function to finish before continuing
  await this.colorPath(path);

  //EDIT: I've also tried:
  this.colorVisited(visitedNodes).then(() => this.colorPath(path));
    return;
  }

  colorVisited = async (visitedNodes) => {
    //do stuff
    return;
  }

  colorPath = async (path) => {
    //do stuff
    return;
  }

【问题讨论】:

标签: javascript asynchronous async-await


【解决方案1】:

他们当然会这样做,这就是它的工作方式。 JavaScript 中没有“中断”或暂停功能。为了实现您的目标,请在第一个 await 的后续 .then() 中调用您的后续函数。

像这样:

helperDikjstras = async() => {/*...*/}
colorVisited = async(visitedNodes, _callback) => {/*...*/}
colorPath = async(path) => {/*...*/}


helperDikjstras()
  .then(() => colorVisited(blah, halb))
  .then(() => colorPath(somePath));

如果您需要在colorPath() 之后运行其他功能,您可以简单地添加更多...

helperDikjstras()
  .then(() => colorVisited(blah, halb))
  .then(() => colorPath(somePath))
  .then(() => doSomethingElse())
  .then(() => andAnother())
  .then(() => etc());

【讨论】:

  • 谢谢,你能澄清一下吗?我有其他函数我想一个接一个地调用,所以我想正确地使用这个语法。你的 helpDikjstras 应该是 helperDiksstras 的函数调用吗?我试过:``` helperDikjstras = async () => { /*..*/ this.colorVisited(visitedNodes).then(() => this.colorPath(path)); } ``` 但它们仍然同时运行this.colorVisited(visitedNodes).then(() => this.colorPath(path));
  • 是的,helperDikjstras。我会编辑答案。您可以根据需要多次添加.then(...)。每个函数将按照.then()s 中列出的顺序运行,并等待前一个函数完成后再运行。
  • 谢谢,我现在明白你的回答了,但为了澄清,我不能在另一个函数中这样做吗?我试过:this.colorVisited(visitedNodes).then(() => this.colorPath(path)); 在我的 helperDikjstra 中,但它们仍然同时运行
  • 为了在 异步 代码 Y 之后运行某些代码 X,您必须使用 JavaScript 中可用的多种机制之一来等待 Y 完成,然后再运行 X。 使用 Promises with Async/Await 语法使用我提供的技术使这变得简单。您最近的评论表明您正试图在函数 Y 内部(作为函数)运行一些代码 X,这打破了范式。所以不,你不能在另一个异步函数中运行异步代码,并期望里面的代码在 after 封闭的函数之后执行。我希望这一切都有意义。
猜你喜欢
  • 1970-01-01
  • 2019-05-24
  • 2020-03-29
  • 1970-01-01
  • 2013-01-23
  • 2019-04-08
  • 2016-10-15
相关资源
最近更新 更多