简体   繁体   中英

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;
}

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()

The easiest way is probably as follows:

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

  some_global = promise;
  return promise;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM