简体   繁体   中英

using async/await without babel-polyfill

my code is following:

  @action async login(payload){
    try {
      this.loginLoading = true
      const data = await request('/admin/login', {
        method: 'post',
        data: payload
      })
      this.logined = true
      localStorage.setItem('token', data.token)
      this.loginLoading = false
    } catch (error) {
      console.log(error)
      message.error('login failed')
      this.logined = false
      this.loginLoading = false
    }

babel-polyfill will transform above code to:

       return _regenerator2.default.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _context.prev = 0;

                this.loginLoading = true;
                _context.next = 4;
                return (0, _request2.default)('/admin/login', {
                  method: 'post',
                  data: payload
                });

              case 4:
                data = _context.sent;

                this.logined = true;
                localStorage.setItem('token', data.token);
                this.loginLoading = false;
                _context.next = 16;
                break;

              case 10:
                _context.prev = 10;
                _context.t0 = _context['catch'](0);

                console.log(_context.t0);
                _message2.default.error('login failed');
                this.logined = false;
                this.loginLoading = false;

              case 16:
              case 'end':
                return _context.stop();
            }
          }

the transformed code will rename variables that hard to read and debug in chrome devl-tool using source map, actually latest chrome is support async/await syntax, so I do not wanna to use babel-polyfill in development.

But if remove babel-polyfill, will throw regeneratorRuntime is not defined.

If you have set your browser targeting to chrome >= 59 then you simply will use the native generators and will never make use of the polyfill.

https://medium.com/@zwacky/add-es7-async-await-support-into-your-non-bleeding-edge-build-process-ad0dded0d002

Interesting to note:

If you only need the generator polyfill — which is needed for async/await — then you can just use facebook/regenerator , which is used by babel-polyfill anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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