简体   繁体   English

是否有可能从函数内部获得异步函数的承诺?

[英]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.我得到 my_func 返回的承诺,并将其分配给一个全局变量。 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/await 模式调用函数时获得该承诺的响应,我认为它会是这样的

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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