0

I have a first function that sends commands and receives data. And a second function to download this data (with href and download). I have a third function that starts function one and then function two but I notice that function two is launched before function one. How do we solve this?

function third(){
    first();
    second();
}
function first(){
//sends and receives commands with websockets
}
function second(){
    console.log("1");
    let save = document.getElementById("photo");
    console.log("2");
    save.href = "http://my_url:my_port/folder/img.jpg";
    console.log("3");
    save.download = "";
    console.log("4");
}

In my console, I can see console.log of the second function before the first function. Why ? Thanks.

Guigui
  • 11
  • 1
  • 2
  • 1
    well, as you've shown it, the first function doesn't output anything - so - as a wild guess ... `asynchrony` is at work - since nothing waits for asynchronous code unless specifically written to do so ... and you've shown nothing in `first()`, and regardless, since you just call it, then nothing asynchronous in `first()` will stop `second()` from merrily chugging along – Bravo Feb 23 '22 at 09:54
  • 2
    You've said the first *"sends and receives commands with websockets"* -- that's [asynchronous](https://developer.mozilla.org/en-US/docs/Glossary/Asynchronous). That means that although `first` may *start* the process, it returns before that process finishes (because it's a synchronous function). So `second` gets called before the asynchronous things happen. If you don't want that to happen, return a [promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises) from `first`, fulfill it when the work is done, and wait for that promise to settle before calling `second`. – T.J. Crowder Feb 23 '22 at 09:57
  • Ok thank you guys, I will find out how to make a promise in javascript – Guigui Feb 23 '22 at 10:02

0 Answers0