0

I don't know if it is possible, but I really want to force a normal function to stop and wait for a async function. Here is a simple example:

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")!

I am not actually working on drawing cats, but I need to know how to do this. I wan't draw_a_cat to wait for get_head_information, meaning draw_cat will not return until it has gotten the head information and drawn the head. The head won't be drawn until the head information has been obtained, so that we can draw the head correctly.

And, the console.log won't happen until the cat is fully drawn and cat_drawn_yet == "true". draw_a_cat is not an async function, meaning it cannot just await get_head_information().

I want the program to stop and wait for the async get_head_information before continuing normally. I know it sounds stupid to freeze everything else, waiting for get_head_information, but I need to do this in a more complicated project where it just makes sense.

1 Answers1

0

You could work with the result from the get_head_information inside the draw_a_cat function without making it async or returning a Promise. However, you would not be able to get a meaningful return value from the draw_a_cat function.

Here is an example using the then method of Promises. The logging of the result "drawn" is moved inside the draw_a_cat function in the callback passed to the then method. Note that if there are more statements after the call to draw_a_cat, they will be executed before the code in the then callback.

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();
Nad Hr
  • 66
  • 5
  • How sad. I was wanting the ability to stop sync processes within asyncs for some other asyncs to have easier control, but I guess I can just use setInterval() if I really need to wait. Of course, usually we don't need to wait in some weird way and can just use promises. – Simon Willover Nov 01 '21 at 18:50