-1

I am calling a function that uses async/await. This function will get a string in the const getinfo

How can I return this "getinfo" string when calling the function like below?

oneFunction("hello")

oneFunction("hello")



function oneFunction(info) {

    (async function () {
        try {

            const getinfo = await somefunction(info)

        } catch (e) {
            console.error(e);
        }
    })()
}
Andreas
  • 1,121
  • 4
  • 17
  • 34
  • 1
    That inner IIFE makes no sense. You should just make `oneFunction` the `async` function. – Bergi Mar 11 '19 at 18:39
  • @Bergi when I look at the example now, I beleive you actually are right. I could in this case just use oneFunction as it is. Thank you! – Andreas Mar 11 '19 at 19:53

1 Answers1

1

You can remove the immediately invoking function expression and instead return the function. Inside the try block return getInfo.

For this example somefunction is returning a promise which is resolved after 3 secs. Since async will return a promise you can get the value inside a then

function oneFunction(info) {

  async function inner() {
    try {

      const getinfo = await somefunction(info);
      return getinfo;

    } catch (e) {
      console.error(e);
    }
  }

  return inner()
}

function somefunction(val) {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve('Value from aysnc ' + val)
    }, 3000);
  })
}

oneFunction("hello").then((data) => {
  console.log(data)

})
brk
  • 48,835
  • 10
  • 56
  • 78