{"record":{"id":"351669f9bde61a80","repo":"oxc-project/oxc","slug":"prefer-async-await-to-the-callback-pattern","errorCode":null,"errorMessage":"Prefer `async`/`await` to the callback pattern","messagePattern":"Prefer `async`/`await` to the callback pattern","errorType":"validation","errorClass":null,"httpStatus":null,"severity":"warning","filePath":"crates/oxc_linter/src/rules/promise/prefer_await_to_callbacks.rs","lineNumber":13,"sourceCode":"use oxc_ast::{\n    AstKind,\n    ast::{Argument, Expression, FormalParameters, MemberExpression},\n};\nuse oxc_diagnostics::OxcDiagnostic;\nuse oxc_macros::declare_oxc_lint;\nuse oxc_semantic::NodeId;\nuse oxc_span::{GetSpan, Span};\n\nuse crate::{AstNode, context::LintContext, rule::Rule};\n\nfn prefer_await_to_callbacks(span: Span) -> OxcDiagnostic {\n    OxcDiagnostic::warn(\"Prefer `async`/`await` to the callback pattern\")\n        .with_help(\"Refactor to use an `async` function with `await` instead of passing callbacks for cleaner error handling and control flow.\")\n        .with_label(span)\n}\n\n#[derive(Debug, Default, Clone)]\npub struct PreferAwaitToCallbacks;\n\ndeclare_oxc_lint!(\n    /// ### What it does\n    ///\n    /// The rule encourages the use of `async/await` for handling asynchronous code\n    /// instead of traditional callback functions. `async/await`, introduced in ES2017,\n    /// provides a clearer and more concise syntax for writing asynchronous code,\n    /// making it easier to read and maintain.\n    ///\n    /// ### Why is this bad?\n    ///\n    /// Using callbacks can lead to complex, nested structures known as \"callback hell,\"","sourceCodeStart":1,"sourceCodeEnd":31,"githubUrl":"https://github.com/oxc-project/oxc/blob/e1e7af627c8843ab64044ed466b128fcc21a035b/crates/oxc_linter/src/rules/promise/prefer_await_to_callbacks.rs#L1-L31","documentation":"Diagnostic from oxlint's port of eslint-plugin-promise's prefer-await-to-callbacks style rule. It reports three callback shapes: calls to a function named `cb`/`callback`, function declarations whose LAST parameter is named `cb`/`callback` (callback-taking definitions), and calls whose last argument is a function whose FIRST parameter is named `err`/`error` when the call is not already inside await/yield. Event wiring (on/once/addEventListener/removeEventListener), array iterators (map/filter/forEach/some/every/find) and lodash-style `_.map` are exempted.","triggerScenarios":"Per the run() visitor: `cb()` / `callback()` callee identifiers; `function getData(id, callback) {}` or `const f = (cb) => {}` last-param named cb/callback; `heart(function(err) {})` / `customMap(errors, (err) => ...)` — a call with a trailing function whose first param is err/error, not under an await/yield ancestor. Passing `something => {}` (non-err name) does not fire; `.map(err => ...)`, `socket.on(\"error\", err => ...)` are exempt.","commonSituations":"Codebases mid-migration from callback APIs (older Node libs, AWS SDK v2, redis clients) to promise APIs; wrapping libraries that only offer callbacks; callbacks that are not error-first (renaming the param avoids the report).","solutions":["Refactor the call site to an awaited promise: promisify the API or use its .async/.promises variant, then `const data = await doThing(arg)`.","Refactor the definition to return a Promise instead of taking a callback: `async function getData(id) { ... }`.","If the callback's first parameter is not an error, rename it (e.g. `(_, result)` or a meaningful name).","For irreducibly callback-based APIs (event emitters, array iteration are already exempt), disable the rule or suppress inline."],"exampleFix":"// before\nfetchData((err, data) => {\n  if (err) throw err;\n  render(data);\n});\n\n// after\nconst data = await fetchData();\nrender(data);","handlingStrategy":"validation","validationCode":"oxlint --promise-plugin src/ # prefer-await-to-callbacks","typeGuard":null,"tryCatchPattern":"// when a callback API is unavoidable at the edge, contain it:\nconst fetchData = () =>\n  new Promise((resolve, reject) => {\n    api.call((err: Error | null, data: unknown) =>\n      err ? reject(err) : resolve(data));\n  });\n// callers then `await fetchData()`","preventionTips":["Promisify library boundaries once (util.promisify or a Promise wrapper) instead of suppressing per call.","Avoid naming callbacks cb/callback in new APIs — the rule keys on those names.","Remember the exemptions (event on/once/addEventListener, array map/filter/...) so legitimate callbacks do not push you toward disabling the rule."],"tags":["promise","async-await","callbacks","oxlint","lint","style"],"backgroundTag":"callback-vs-async-await","analyzedSha":"e1e7af627c8843ab64044ed466b128fcc21a035b","analyzedAt":"2026-08-20T07:01:07.079Z","contentChangedAt":"2026-08-20T07:01:07.079Z","schemaVersion":2},"datasetVersion":"2026-09-14T05:17:10.506Z"}