How to know if a function is async?

后端 未结 8 802
别跟我提以往
别跟我提以往 2020-12-01 00:55

I have to pass a function to another function, and execute it as a callback. The problem is that sometimes this function is async, like:

async function() {
          


        
8条回答
  •  温柔的废话
    2020-12-01 01:35

    You can assume at begin that callback is promise:

    export async function runSyncOrAsync(callback: Function) {
    
      let promisOrValue = callback()
      if (promisOrValue instanceof Promise) {
        promisOrValue = Promise.resolve(promisOrValue)
      }
      return promisOrValue;
    }
    

    and them in your code you can do this:

    await runSyncOrAsync(callback)
    

    which will solve your problem with unknowing callback type....

提交回复
热议问题