Order of execution issue javascript

后端 未结 2 1862
生来不讨喜
生来不讨喜 2020-12-07 06:16

In my code below, 5 always prints before 4. I thought because the callback to postUsers was in a return statement from matchAgainstAD it would wait

2条回答
  •  春和景丽
    2020-12-07 06:49

    ad.findUser takes a callback that contains the console.log(4). That function is async, and will hit your callback when the IO operation has completed.

    On the other hand, postUsers is called completely synchronously, so it will hit console.log(5) before ad.findUser enters your callback.

    A simple way to fix this is to call postUsers from inside of your ad.findUser callback.

    I would suggest looking into the promise pattern for JavaScript to manage dependencies between async operations. There are several popular libraries (Q and RSVSP.js being a couple of them).

提交回复
热议问题