Node.js: Asynchronous Callback Execution. Is this Zalgo?

后端 未结 2 979
挽巷
挽巷 2020-12-22 13:04

Executing the below using node - 6.0.

function A(callback) {
  console.log(\'A\');
  callback();
}

function B() {
  console.log(\'B\')
}

f         


        
2条回答
  •  南方客
    南方客 (楼主)
    2020-12-22 13:48

    No, neither of these is zalgo. Your first A function always calls its callback synchronously, and should be documented as such. Your second A function always calls its callback asynchronously, and should be documented as such. Nothing is wrong with that, we use thousands of these every day. The outputs A C B and A B C are deterministic.

    Zalgo refers to the uncertainty whether a callback is asynchronous or not.

    function A(callback) {
      console.log('A');
      if (Math.random() < 0.5) {
        callback();
      } else {
        process.nextTick(callback);
      }
    }
    

    The output of the invocation A(C); B(); would be totally unpredictable.

提交回复
热议问题