繁体   English   中英

如何在功能中摆脱异步?

[英]How to get rid of async in function?

假设我有这段代码:

const myFunction = async => {
  const result = await foobar()
}

const foobar = async () => {
  const result = {}
  result.foo = await foo()
  result.bar = await bar()
  return result
}

我想要这个:

const myFunction = () => {
  const result = foobar()
}

我试着像这样包裹foob​​ar

const foobar = async () => {
  return (async () => {
    const result = {}
    result.foo = await foo()
    result.bar = await bar()
    return result
  })()
}

但这仍然是一个承诺

我不能在myFunction中使用.then ,我需要foob​​ar返回结果变量而不是promise。

问题是myFunction是一个异步函数,它将返回一个promise但它应该返回undefine我需要摆脱myFunction中的异步。

编辑:正如Sebastian Speitel所说,我想将myFunction转换为同步

编辑2:到Shilly,我使​​用nightwatch进行end2end测试,nightwatch将调用myFunction()如果执行函数没有错误它将完美运行,如果有错误,那么nightwatch的虚拟机将永远运行而不是停止,如果被调用的函数是异步的,则会出现此问题。

要将异步函数更改为普通的同步函数,您只需删除async关键字,因此所有await该函数中的关键字。

const myFunction = async () => {
    const result = await foobar();
    // ...
    return 'value';
};

// becomes

const myFunction = () => {
    const result = foobar();
    // ...
    return 'value';
};

但是,您应该记住一个简单的规则。

  1. 如果返回值取决于已解析的promise(s)的值,​​则无法将异步函数更改为同步函数。

这意味着处理其体内promises的函数,但返回值不依赖于那些已解析的promises的函数完全可以作为同步函数。 在大多数其他方案中,您无法删除异步行为。

以下代码为您提供了一个示例,假设myFunction的返回值不依赖于已解析的promise。

const myFunction = () => {
    const result = foobar();

    result.then(data => doSomethingElse(data))
          .catch(error => console.error(error));

    return 'some value not dependent on the promise result';
};

如果您想了解有关promises的更多信息,我建议您查看promises指南async / await页面。

您是否考虑过使用.executeAsync()然后让promise调用.done()回调? 这样就可以包装foobar并在该包装器中保持异步或任何.then()调用。

我的夜班知识非常陈旧,但可能是这样的:

() => {
  client.executeAsync(( data, done ) => {
    const result = await foobar();
    done( result );
  });
};

要么:

  () => {
    client.executeAsync(( data, done ) => foobar().then( result => done( result )));
  };

任何标记为async函数都将返回Promise。 这个:

const foobar = async () => {
  return 7;
}

将返回7的Promise。这完全独立于调用foobar的函数是否async ,或者在调用它时使用await与否。

所以,你的问题不是(仅)与myFunction :使用async foobar强制它总是返回一个Promise。

现在,说, 你可能无法实现你想要的 Async-Await 只是promises的语法糖 你正在尝试从异步操作返回一个同步值 ,这在javascript中基本上是禁止的。

您在此处缺少对代码的同步和异步性质的非常重要的理解。

并非每个异步函数都可以转换为同步函数。 您可以使用回调模式而不是await / async,但我怀疑这对您有用。

相反,我建议您只使用await ,就像在第一个代码示例中一样,并将函数保留为异步,它不应该损害您的逻辑。

看一下这个

    function foo(){
      return 'foo'
    }
    function bar(){
      return 'bar'
    }
    const foobar = () => {
        return new Promise((resolve)=>{
          let result = {}
          result.foo = foo()
          result.bar = bar()
          return resolve(result)
        })
    }

    const myFunction = () => {
      const result = foobar()
      let response = {}
      result.then(val=>{
        response = Object.assign({}, val);
        return response
      });
    }

    var test = myFunction()
    console.log(test)

暂无
暂无

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

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