【问题标题】:Can we call non-async function from async function?我们可以从异步函数中调用非异步函数吗?
【发布时间】:2019-08-18 21:57:19
【问题描述】:

我在从函数方法调用非异步函数时遇到问题。有没有办法做到这一点?

例子:

async function myMethod()
{
  console.log('In async method');
  nonasyncmethod(); 
}

function nonasyncmethod()
{
  console.log('In non-async method');
}

【问题讨论】:

  • 如果您谈论的是对象方法,那么您可能需要将该方法称为this.nonasyncmethod()。但这就是方法通常的工作方式,与异步无关。如果这不能解决您的问题,请提供minimal reproducible example
  • 你的示例代码有有效的语法吗?
  • 我觉得不错。
  • @SyedMohamedAladeen 不,我的问题与那个问题相反

标签: javascript function ecmascript-6


【解决方案1】:

是的,您可以在 async 函数中调用异步和同步函数 - 它们不必全部异步(当然,拥有 async 函数的主要原因是对于异步函数,但它们也适用于同步函数):

async function myMethod() {
  console.log('In async method');
  nonasyncmethod();
}

function nonasyncmethod() {
  console.log('In non-async method');
}

myMethod();

【讨论】:

    猜你喜欢
    • 2014-06-14
    • 1970-01-01
    • 2020-03-09
    • 2019-10-07
    • 1970-01-01
    • 1970-01-01
    • 2020-04-20
    • 1970-01-01
    • 2017-08-13
    相关资源
    最近更新 更多