LT-Sites
LT-Sites

Reputation: 415

How to obtain a returning status 'true' or 'false' from async functions execution success or failure

I have a question

How to make a functional code with the basic idea of this example?

Like a success or fail event based result for asynchronous code execution.

async function doSomeThing ( ...params ){
 //Some async thing to do with params
}

function callToAsync ( doSomething() ){
 //Some implementation for doSomething() success
 return true;
 //Some code implementation for doSomething() fail or error happens
 console.log(error);
 return false;
}

I'm learning a little bit about asynchronous javascript code.

thanks for any ideas.

Upvotes: 2

Views: 1524

Answers (2)

muka.gergely
muka.gergely

Reputation: 8329

If you are using async-await don't forget to wrap it in try-catch - it's worth the effort.

Creating a function that accepts a function as a parameter (argument) is a bit trickier than the same thing with simple values - and even "worse" if said paramter-function is async.

async function doSomething() {
  // always wrap the async call in a try-catch block!
  try {
    const c = await !!Math.floor(Math.random() + 0.5) // return true or false
    return c
  } catch (err) {
    console.log(err)
  }
};

// creating an async function with a function as an argument
async function callToAsync(fn) {
  if (typeof fn === 'function') {
    try {
      if (await fn()) {
        return 'this is true'
      } else {
        return 'this is false'
      }
    } catch (err) {
      console.log(err)
    }
  }
};

// self-calling async function
(async function() {
  for (let i = 0; i < 10; i++) {
    try {
      const response = await callToAsync(() => doSomething())
      console.log(`${ i + 1 }. ${ response }`)
    } catch (err) {
      console.log(err)
    }
  }
})();

Upvotes: 1

3limin4t0r
3limin4t0r

Reputation: 21120

Here is a basic example of what I think you want.

async function doSomeThing() {
  const randomNr = await Math.random(); //<- await for demonstration purposes
  if (randomNr < 0.2) {
    throw `${randomNr} should be >= 0.2`;
  } else {
    return randomNr;
  }
}

function callToAsync() {
  return doSomeThing() // <- return here is important
  .then(result => {
    console.log(`SUCCES: ${result}`);
    return true;
  })
  .catch(error => {
    console.error(`ERROR: ${error}`);
    return false;
  });
}

callToAsync()
.then(bool => {
  console.log(bool);
});

Like shown in the code the first return in callToAsync is important. This first return makes sure a promise is returned to the caller which will hold the boolean value once resolved.

The callToAsync function could also be written as:

async function callToAsync() {
  try {
    const result = await doSomeThing();
    console.log(`SUCCES: ${result}`);
    return true;
  } catch (error) {
    console.error(`ERROR: ${error}`);
    return false;
  }
}

Upvotes: 3

Related Questions