Do I need to be concerned with race conditions with asynchronous Javascript?

前端 未结 5 914
悲哀的现实
悲哀的现实 2020-11-29 06:12

Suppose I load some Flash movie that I know at some point in the future will call window.flashReady and will set window.flashReadyTriggered = true.

5条回答
  •  北荒
    北荒 (楼主)
    2020-11-29 06:31

    Yes, of course there are race conditions in Javascript. It is based on the event loop model and hence exhibits race conditions for async computations. The following program will either log 10 or 16 depending on whether incHead or sqrHead is completed first:

    const rand = () => Math.round(Math.random() * 100);
    
    const incHead = xs => new Promise((res, rej) =>
      setTimeout(ys => {
        ys[0] = ys[0] + 1;
        res(ys);
      }, rand(), xs));
    
    const sqrHead = xs => new Promise((res, rej) =>
      setTimeout(ys => {
        ys[0] = ys[0] * ys[0];
        res(ys);
      }, rand(), xs))
    
    const state = [3];
    
    const foo = incHead(state);
    
    const bar = sqrHead(state);
    
    Promise.all([foo, bar])
      .then(_ => console.log(state));

提交回复
热议问题