Check if a js function is called using await?

笑着哭i 提交于 2021-01-27 23:13:48

问题


I have a checkPermission function in which I pull session, reach database and confirm permission. If the action is not permitted, the function throws.

await checkPermission("USER_READ"); // This will throw if not permitted.
// Do permission specific stuff.

Problem is if I forget await, it will not wait and move to unpermitted code. Can I programatically check in checkPermission function if await is used so I can throw if await is not used? Or is there any other way I can enforce await for a given function and throw if not used.

Note: I know I can put it in an if and check if it returns Promise. But that is not what I am asking.


回答1:


You can easily accomplish this by using eslint and add it as part of your CI pipeline

Disallow async functions which have no await expression (require-await)

   eslint require-await: "error"

https://eslint.org/docs/rules/require-await




回答2:


The best way to solve this is to use a linter, if for some reason you can't, you can perform a runtime check that .then was indeed called and log a warning or something if it wasn't

const mustCallThen = fn => (...args) => {
  const timeout = setTimeout(() => {
    console.warn(fn, '.then was not called')
  })

  const then = (resolve, reject) => {
    clearTimeout(timeout)
    return fn(...args).then(resolve, reject)
  }

  return { then, catch: reject => then(null, reject) }
}

async function checkPermission(permission) {
  // some async code
  return true
}

// usage example:
const yo = mustCallThen(checkPermission)
// yo is now the same function but will warn you if .then was not called right after:
yo()
// will log:
// async function checkPermission(permission) .then was not called
await yo() // wil not log


来源:https://stackoverflow.com/questions/63765159/check-if-a-js-function-is-called-using-await

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!