【问题标题】:how to make synchronous function stop and wait for asynchronous function to finish executing in JavaScript如何使同步函数停止并等待异步函数在JavaScript中完成执行
【发布时间】:2021-11-26 17:16:30
【问题描述】:

我不知道这是否可能,但我真的很想强制一个正常的函数停止并等待一个异步函数。这是一个简单的例子:

function draw_a_cat(){
  draw_cat_body();

  // get_head_information is asynchronous, and I want to STOP execution and wait for it to get info we need in order to draw the cat.
  wait for get_head_information();

  draw_head();
  display_cat_name();

  return true;
}

cat_drawn_yet = draw_a_cat();
console.log("drawn")!

我实际上并没有画猫,但我需要知道如何做到这一点。我不想draw_a_cat 等待get_head_information,这意味着draw_cat 在获得头部信息并绘制头部之前不会返回。获取头部信息后才会绘制头部,这样我们才能正确绘制头部。

而且,console.log 不会发生,直到猫被完全绘制和cat_drawn_yet == "true"draw_a_cat 不是异步函数,这意味着它不能只是 await get_head_information()

我希望程序在正常继续之前停止并等待异步 get_head_information。我知道冻结其他所有内容,等待get_head_information 听起来很愚蠢,但我需要在更复杂的项目中执行此操作,这样才有意义。

【问题讨论】:

标签: javascript async-await wait


【解决方案1】:

可以draw_a_cat 函数中处理来自get_head_information 的结果,而无需将其设为async 或返回Promise。但是,您将无法从 draw_a_cat 函数获得有意义的返回值。

这是一个使用 Promises 的 then 方法的示例。 “绘制”结果的日志记录在传递给 then 方法的回调中移动到 draw_a_cat 函数内。 请注意,如果在调用draw_a_cat 之后还有更多语句,它们将在then 回调中的代码之前执行。

const draw_cat_body = () => { };
const draw_head = () => { };
const display_cat_name = () => { };
const get_head_information = () => Promise.resolve('round and fluffy');

function draw_a_cat() {
  draw_cat_body();

  // can wait here
  get_head_information()
    .then(info => {
      // you can work with what get_head_information returned
      draw_head(info); // assuming drawing the head is synchronous
      display_cat_name();
      console.log("drawn");
    })
    .catch(err => {
      console.log(err);
    });
}
// can NOT wait here
draw_a_cat();

【讨论】:

  • 多么悲伤。我希望能够在异步中停止同步进程,以便其他一些异步更容易控制,但我想如果我真的需要等待,我可以使用 setInterval()。当然,通常我们不需要以某种奇怪的方式等待,只需使用 Promise 即可。
猜你喜欢
  • 2019-11-07
  • 1970-01-01
  • 1970-01-01
  • 2019-06-16
  • 2019-12-30
  • 2017-05-18
  • 2019-11-29
  • 1970-01-01
  • 2019-05-17
相关资源
最近更新 更多