Home > Back-end >  is it ok to pass async function where non async function needed?
is it ok to pass async function where non async function needed?

Time:12-02

as below, an async function was given for a paramter where non-async function expected, but it worked, why?


function getCallback(param, callback) {
  setTimeout(() => {
    callback && callback(param);
  }, 1);
}

getCallback(13, async (param) => {
  console.log(param);
});

---
13

CodePudding user response:

It worked, why?

Because an async function is just a function that returns a promise and can be called like any other function. Your getCallback ignores the return value of callback(), so it doesn't matter what it returns.

Is it ok to pass async function where no async function is needed?

No, it generally is not ok to pass an async function (or another function that returns a promise) to a function that doesn't expect the callback to return a promise. Promises should not be ignored, they should be .then()-chained or awaited, and they need special error handling. If the getCallback does not handle (promise) errors, you must not pass a callback that errors.

  • Related