Determine whether a method is synchronous or asynchronous

前端 未结 3 824
暖寄归人
暖寄归人 2021-02-07 06:13

In node.js, is it possible to determine (using a function) whether a method is synchronous or asynchronous?

I\'d like to write a function that does the following:

<
3条回答
  •  失恋的感觉
    2021-02-07 06:38

    You don't necessarily know. A function could even be randomly synchronous or asynchronous.

    For example, a function that takes another function could execute that function immediately, or it could schedule to execute it at a later time using setImmediate or nextTick. The function could even randomly choose to call its passed function synchronously or asynchronous, such as:

    console.log('Start')
    
    function maybeSynchOrAsync(fun) {
    
      var rand = Math.floor((Math.random() * 2))
    
      if (rand == 0) {
        console.log('Executing passed function synchronously')
        fun()
        console.log('Done.')
      } else {
        console.log('Executing passed function asynchronously via setImmediate')
        setImmediate(fun)
        console.log('Done.')
      }
    }
    
    maybeSynchOrAsync(function () { console.log('The passed function has executed.') });
    

    Further, technically speaking, every function call is synchronous. If you call a function F, and F queues a callback function to be invoked later (using setTimeout or whatever mechanism), the original function F still has a synchronous return value (whether it's undefined, a promise, a thunk, or whatever).

提交回复
热议问题