简体   繁体   English

如何在功能中摆脱异步?

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

Let's say I have this code: 假设我有这段代码:

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

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

And I want this: 我想要这个:

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

I tried to wrap foobar like this: 我试着像这样包裹foob​​ar

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

But this still return a promise 但这仍然是一个承诺

I can't use .then in myFunction , I need that foobar returns the result variable instead a promise. 我不能在myFunction中使用.then ,我需要foob​​ar返回结果变量而不是promise。

The problem is that myFunction is an async function and it will return a promise but It should return undefine I need to get rid of async in myFunction . 问题是myFunction是一个异步函数,它将返回一个promise但它应该返回undefine我需要摆脱myFunction中的异步。

Edit: as Sebastian Speitel said, I want to convert myFunction to sync 编辑:正如Sebastian Speitel所说,我想将myFunction转换为同步

Edit 2: to Shilly, I am using nightwatch for end2end test, nightwatch will call myFunction() if there are no errors in the execution of the function it will run perfectly, if there's an error then nightwatch's virtual machines will run forever instead stop, this problem happens if the called function is async. 编辑2:到Shilly,我使​​用nightwatch进行end2end测试,nightwatch将调用myFunction()如果执行函数没有错误它将完美运行,如果有错误,那么nightwatch的虚拟机将永远运行而不是停止,如果被调用的函数是异步的,则会出现此问题。

To change an asynchronous function into a normal synchronous function you simply have to drop the async keyword and as a result all await keywords within that function. 要将异步函数更改为普通的同步函数,您只需删除async关键字,因此所有await该函数中的关键字。

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

// becomes

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

You should however keep one simple rule in mind. 但是,您应该记住一个简单的规则。

  1. You can't change a asynchronous function into a synchronous function if the return value depends on the value(s) of the resolved promise(s). 如果返回值取决于已解析的promise(s)的值,​​则无法将异步函数更改为同步函数。

This means that functions that handle promises inside their body, but from whom the return value doesn't depend on those resolved promises are perfectly fine as synchronous functions. 这意味着处理其体内promises的函数,但返回值不依赖于那些已解析的promises的函数完全可以作为同步函数。 In most other scenarios you can't drop the asynchronous behaviour. 在大多数其他方案中,您无法删除异步行为。

The following code gives you an example for your situation, assuming the return value of myFunction doesn't depend on the resolved promise. 以下代码为您提供了一个示例,假设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';
};

If you want to learn more about promises I suggest checking out the promises guide and the async / await page. 如果您想了解有关promises的更多信息,我建议您查看promises指南async / await页面。

Have you looked into using .executeAsync() and then having the promise call the .done() callback? 您是否考虑过使用.executeAsync()然后让promise调用.done()回调? That way it should be possible to wrap foobar and just keep either the async or any .then() calls inside that wrapper. 这样就可以包装foobar并在该包装器中保持异步或任何.then()调用。

My nightwatch knowledge is very stale, but maybe something like: 我的夜班知识非常陈旧,但可能是这样的:

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

or: 要么:

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

Any function marked with async will return a Promise. 任何标记为async函数都将返回Promise。 This: 这个:

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

Will a return a Promise of 7. This is completely independent of wether the function that calls foobar is async or not, or uses await or not when calling it. 将返回7的Promise。这完全独立于调用foobar的函数是否async ,或者在调用它时使用await与否。

So, you're problem is not (only) with myFunction : is foobar using async which forces it to always return a Promise. 所以,你的问题不是(仅)与myFunction :使用async foobar强制它总是返回一个Promise。

Now, said that, you probably can't achieve what you want . 现在,说, 你可能无法实现你想要的 Async-Await is only syntax sugar for promises . Async-Await 只是promises的语法糖 What you're trying is to return a synchronous value from an asynchronous operation , and this is basically forbidden in javascript. 你正在尝试从异步操作返回一个同步值 ,这在javascript中基本上是禁止的。

You're missing very important understanding here between the synchronous and asynchronous nature of the code. 您在此处缺少对代码的同步和异步性质的非常重要的理解。

Not every async function can be converted to synchronous function. 并非每个异步函数都可以转换为同步函数。 You can use callback pattern instead of await/async, but I doubt that would be useful to you. 您可以使用回调模式而不是await / async,但我怀疑这对您有用。

Instead I would recommend you just use await , as in your first code example, and leave functions as async, it shouldn't harm your logic. 相反,我建议您只使用await ,就像在第一个代码示例中一样,并将函数保留为异步,它不应该损害您的逻辑。

Check this out 看一下这个

    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.

相关问题 eslint警告意外的未命名的异步函数,无论如何要摆脱它? - eslint Warning Unexpected unnamed async function , anyway to get rid if it? 如何摆脱这个函数中的“with()”? - how do I get rid of “with()” in this function? 在异步函数上调用 then 之后如何获取异步函数的返回值 - how to get the return value of an async function after then is called on the async function 尝试在React中异步操作创建者时如何摆脱使用绝对URL错误? - How to get rid of use absolute urls error when trying to async action creators in React? 如何用我的JavaScript函数摆脱周末约会? - How to get rid of weekend dates with my javascript function? 如何摆脱该函数的第一个if语句? - How can I get rid of the first if statement from this function? 我如何摆脱将“新功能”放在功能之前的问题 - How can i get rid of putting “new” before a function 如何摆脱这种自调用功能? - How can I get rid of this self-calling function? 如何摆脱 Angular aot 编译中装饰器不支持的函数调用? - How to get rid of Function calls are not supported in decorators in Angular aot compiling? 如何摆脱这个JS错误:TypeError:$(...)。validate不是一个函数 - How do I get rid of this JS error: TypeError: $(…).validate is not a function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM