在各处使用异步函数的(潜在)缺点是什么? [英] What is the (potential) drawback of using async functions everywhere?

查看:123
本文介绍了在各处使用异步函数的(潜在)缺点是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Javascript.这听起来像是个疯狂的主意,但我在Google上找不到明确的答案.我可以随处都可以用async function替换所有常规函数/方法吗?我的意思是,这似乎没有任何弊端,这使事情变得如此简单.在情况仅涉及同步步骤的情况下,您无需使用await,它将像正常功能一样工作.容易!

I am learning Javascript. This may sound like a crazy idea but I don't find clear answers on Google. Can I just replace all my regular functions/methods with async function everywhere? I mean there seems to be no downsides to this and it makes things so much simpler. Where the situation only involves synchronous steps, you just don't use await and it will work just like normal functions. Easy!

我个人觉得必须区分async功能和正常功能是不必要的麻烦.就像驾驶手动变速箱汽车一样,汽车本身可以轻松地自行处理齿轮传动.

Personally I find having to distinguish async functions and normal functions unnecessarily burdensome. It's like driving a manual transmission car, where the car itself could easily handle the gearing by itself.

我在这里想念东西吗?

推荐答案

async函数始终返回Promises.这意味着,只要您处理异步内容,就必须先将返回的Promise转换为值,然后才能使用它.例如:

async functions always return Promises. This means that anytime you're not dealing with something asynchronous, you would have to convert the returned Promise into a value before you could use it. For example:

const return4 = async () => 4;
console.log(4 + return4());

相反,您将不得不使用(不必要的罗y):

Instead, you would have to use the (unnecessarily wordy):

const return4 = async () => 4;
(async () => {
  console.log(4 + await return4());
})();

(或在使用前在return4调用中呼叫.then)

(or call .then on the return4 call before using it)

另一方面,如果return4不是async,那么仅console.log(4 + return4());当然也可以.

If return4 was not async, on the other hand, of course console.log(4 + return4()); alone would work just fine.

async函数的另一个问题是将它们转换为ES5代码(允许与IE等过时的浏览器兼容)需要regenerator-runtime,这是非常的重量级.例如,使用Babel转译以下单行:

Another problem with async functions is that transpiling them to ES5 code (which allows for compatibility with obsolete browsers like IE) requires regenerator-runtime, which is very heavyweight. For example, transpiling the following single line with Babel:

const foo = async () => console.log('async!');

将其插入 repl 时,您会得到:

When you plug it into the repl, you get:

"use strict";

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
  try {
    var info = gen[key](arg);
    var value = info.value;
  } catch (error) {
    reject(error);
    return;
  }
  if (info.done) {
    resolve(value);
  } else {
    Promise.resolve(value).then(_next, _throw);
  }
}

function _asyncToGenerator(fn) {
  return function() {
    var self = this,
      args = arguments;
    return new Promise(function(resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}

var foo =
  /*#__PURE__*/
  (function() {
    var _ref = _asyncToGenerator(
      /*#__PURE__*/
      regeneratorRuntime.mark(function _callee() {
        return regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch ((_context.prev = _context.next)) {
              case 0:
                return _context.abrupt("return", console.log("async!"));

              case 1:
              case "end":
                return _context.stop();
            }
          }
        }, _callee);
      })
    );

    return function foo() {
      return _ref.apply(this, arguments);
    };
  })();

这也取决于脚本中已经包含的regeneratorRuntime,这是700几行代码,您可以看到

which also depends on regeneratorRuntime already being included in the script, which is 700-something lines of code that you can see here.

在功能较弱的系统上,这可能会对性能造成不小的影响.这就是为什么有些人(例如,使用AirBNB样式指南)更喜欢从不使用async函数的原因,即使它们使脚本的异步控制流程更加清晰.

On less powerful systems, this can result in a not-insignificant performance hit. This is why some (such as with the AirBNB style guide) prefer to never use async functions, even if they make the asynchronous control flow of the script clearer.

这篇关于在各处使用异步函数的(潜在)缺点是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆