user81993
user81993

Reputation: 6613

Is it possible to get the promise of an async function from inside the function itself?

Say I have

function my_func() {
    var promise = new Promise((resolve)=>{
        resolve(5);
    });
    some_global = promise;
    return promise;
}

I get the promise being returned by my_func and also assign it to a global variable. Is it possible to also do this while using the async syntax? Sorta like

async function my_func() {
    some_global = ???
    return 5;
}

Upvotes: 2

Views: 36

Answers (2)

Hermes Hdez
Hermes Hdez

Reputation: 21

if you want to set the promise to your global variable and get the response of that promise when you call the function with the async/await pattern i think it would be like this

async function my_func() {
  some_global = new Promise((resolve, reject) => {
    resolve(5);
    reject('error');
  })

  return await some_global;
}

async function func_call() {
  console.log(await my_func());
}

func_call()

Upvotes: 1

David Callanan
David Callanan

Reputation: 5968

The easiest way is probably as follows:

function my_func() {
  let promise = (async () => {
    return 5;
  });

  some_global = promise;
  return promise;
}

Upvotes: 0

Related Questions