标签: ecmascript-next

使用装饰器将属性分配给非原型

我正在构建前端/后端数据结构之间的简单映射.为了做到这一点,我创建了一个看起来如下的装饰器:

function ApiField(
    apiKey: string,
    setFn: (any) => any = (ret) => ret,
    getFn: (any) => any = (ret) => ret
) {
    return function (target: AbstractModel, propertyKey: string) {
        target.apiFieldsBag = target.apiFieldsBag || {};
        _.assign(
            target.apiFieldsBag,
            {
                [propertyKey]: {
                    apiKey: apiKey,
                    setFn: setFn,
                    getFn: getFn
                }
            }
        );
    };
}
Run Code Online (Sandbox Code Playgroud)

这就是我使用它的方式:

class AbstractCar {
    @ApiField('id')
    public id: string = undefined;
}

class BMW extends AbstractCar {
    @ApiField('cylinders')
    public cylinderCount: number;
}

class VW extends AbstractCar {
    @ApiField('yearCompanyFounded')
    public yearEstablished: …
Run Code Online (Sandbox Code Playgroud)

javascript decorator typescript ecmascript-next

8
推荐指数
1
解决办法
515
查看次数

异步/等待不等待

我遇到了一个我不完全理解的问题.我觉得有可能是我没有掌握的概念,可以优化的代码,以及可能出现的错误.

大大简化整体流程:

  1. 请求外部API
  2. 解析并扫描返回的JSON对象以获取链接引用
  3. 如果找到任何链接引用,则会生成其他请求以使用真实JSON数据填充/替换链接引用
  4. 更换所有链接引用后,将返回原始请求并用于构建内容

这是原始请求(#1):

await Store.get(Constants.Contentful.ENTRY, Contentful[page.file])
Run Code Online (Sandbox Code Playgroud)

Store.get表示为:

async get(type, id) {
    return await this._get(type, id);
}
Run Code Online (Sandbox Code Playgroud)

哪个电话:

_get(type, id) {
    return new Promise(async (resolve, reject) => {
        var data = _json[id] = _json[id] || await this._api(type, id);

        console.log(data)

        if(isAsset(data)) {
            resolve(data);
        } else if(isEntry(data)) {
            await this._scan(data);

            resolve(data);
        } else {
            const error = 'Response is not entry/asset.';

            console.log(error);

            reject(error);
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

API调用是:

_api(type, id) {
    return new Promise((resolve, reject) => {
        Request('http://cdn.contentful.com/spaces/' + Constants.Contentful.SPACE …
Run Code Online (Sandbox Code Playgroud)

node.js reactjs webpack babeljs ecmascript-next

8
推荐指数
1
解决办法
4731
查看次数

用于JS装饰器的ESLint意外字符'@'

我正在尝试在我的JS项目中使用装饰器,但是ESLint正在抛出一个错误,指出@符号是一个意外的字符.

我的代码:

@observable items = [];
Run Code Online (Sandbox Code Playgroud)

我的.eslintrc:

{
    "parserOptions": {
            "ecmaVersion": 6,
            "ecmaFeatures": {
                "jsx": true
            },
            "sourceType": "module"
    },
    "env": {
            "browser": true,
            "node": true,
            "es6": false
    },
    "ecmaFeatures": {
            "modules": true
    },
    "rules": {
        "strict": [
            2,
            "global"
        ],
        "quotes": [
            2,
            "single"
        ],
        "indent": [
            2,
            4
        ],
        "eqeqeq": [
            2,
            "smart"
        ],
        "semi": [
            2,
            "always"
        ],
        "max-depth": [
            2,
            4
        ],
        "max-statements": [
            2,
            15
        ],
        "complexity": [
            2,
            5
        ]
    }
}
Run Code Online (Sandbox Code Playgroud)

javascript eslint ecmascript-next

8
推荐指数
2
解决办法
8749
查看次数

Arrow使用Babel作为类属性

有人可以解释React中的Babel如何支持胖箭头函数作为类属性?使用Babel 尝试一下我可以看到它们不受支持:

class Question {

  // Property (not supported)
  myProp = () => {
    return 'Hello, world!';
  }

  // Method (supported)
  myFunc() {
    return 'Hello, world!';
  }

}
Run Code Online (Sandbox Code Playgroud)

ES6中不支持类属性(如果我错了,请纠正我),但是在React(使用Babel)中它们可以工作.

我可以使用TypeScript Playground看到方法和属性之间的区别,但我无法清楚地了解Babel是否支持它们.有插件吗?

更新:
我可以看到他们支持使用"babel-preset-stage-0".

javascript class reactjs babeljs ecmascript-next

8
推荐指数
1
解决办法
3711
查看次数

JS&ES6:从类中访问静态字段

在ES6中,给出以下示例:

export default class MyStyle extends Stylesheet {
   static Color = {
      mainDark: '#000'
   }
   static Comp = {
      ...
      color: Color.mainDark
   }
}
Run Code Online (Sandbox Code Playgroud)

如何访问Color.mainDark(静态字段)?

javascript reactjs ecmascript-next

7
推荐指数
1
解决办法
3775
查看次数

ES7异步功能和承诺之间的技术差异?

我试图更好地理解async functionJavaScript在技术上是什么,即使我基本上知道如何使用它们.

对async/await的许多介绍都相信async函数基本上只是一个承诺,但事实上并非如此(至少不是Babel6-transiled代码):

async function asyncFunc() {
  // nop
}

var fooPromise = new Promise(r => setTimeout(r, 1));

console.clear();

console.log("typeof asyncFunc is", typeof asyncFunc); // function
console.log("typeof asyncFunc.next is", typeof asyncFunc.next); // undefined
console.log("typeof asyncFunc.then is", typeof asyncFunc.then); // undefined

console.log("typeof fooPromise is", typeof fooPromise); // object
console.log("typeof fooPromise.next is", typeof fooPromise.next); // undefined
console.log("typeof fooPromise.then is", typeof fooPromise.then); // function
Run Code Online (Sandbox Code Playgroud)

尽管如此,它绝对有可能成为await一种承诺await fooPromise().

  • 它是一个async funtion属于自己的东西,await …

javascript babeljs ecmascript-next

7
推荐指数
1
解决办法
526
查看次数

为什么等待*从异步/等待提议中删除?

它似乎唯一记录的地方是这个问题线程实际规范.但是,删除的原因并没有张贴在我能找到的任何地方.

新推荐的方式似乎是await Promise.all(),但我很好奇为什么await*被删除.

javascript async-await ecmascript-next

7
推荐指数
1
解决办法
3433
查看次数

从异步函数返回的promise中获取值

我已经习惯了提出的异步/等待语法,并且有一些不直观的行为.在"async"函数中,我可以在console.log中找到正确的字符串.但是,当我尝试返回该字符串时,它会返回一个promise.

检查此条目:async/await隐式返回promise?,很明显,任何"async function()"都会返回一个promise,而不是一个值.没关系.但是,您如何获得价值?如果唯一的答案是"回调",那很好 - 但我希望可能会有更优雅的东西.

// src 
// ==========================================

require("babel-polyfill");
var bcrypt = require('bcrypt');

var saltAndHash = function(password){
  var hash;
  return new Promise(function(resolve, reject){
    bcrypt.genSalt(10, function(err, salt) {
      bcrypt.hash(password, salt, function(err, hash) {
          resolve(hash);
      });
    });
  })
}

var makeHash = async function(password){
  var hash = await saltAndHash(password);
  console.log("inside makeHash", hash); 
  return(hash); 
}

// from test suite
// ==========================================

describe('Bcrypt Hashing', function(){

  it('should generate a hash', function(){
    var hash = makeHash('password');
    console.log("inside test: ", hash); 
    should.exist(hash);
  })

}) …
Run Code Online (Sandbox Code Playgroud)

javascript async-await ecmascript-next

7
推荐指数
1
解决办法
957
查看次数

依赖注入库 - 重命名注入的值

我想通过名字注入lodash,如下所示:

let val = function(lodash){
   // lodash will be injected, simply by using require('lodash');
};
Run Code Online (Sandbox Code Playgroud)

但是说我要重命名导入,我想做这样的事情:

let val = function({lodash:_}){

};
Run Code Online (Sandbox Code Playgroud)

要么

let val = function(lodash as _){

};
Run Code Online (Sandbox Code Playgroud)

有没有办法用ES6/ES7/ES8或TypeScript做到这一点?

请注意,这个DI框架比仅需要('x')做更多的工作......它将首先尝试注入其他值,如果没有其他值,那么它将尝试要求该值.

另请注意,这里的要求是当您调用val.toString()时,"lodash"将被视为参数名称.但是在函数体内的运行时会看到_而不是lodash.这是因为为了注入lodash,我们调用fn.toString()来获取参数名称.

javascript dependency-injection node.js typescript ecmascript-next

7
推荐指数
1
解决办法
323
查看次数

'string' 类型不存在属性 'trimLeft'。Lib: ["dom", "es2018"]

运行以下代码时出现此错误

let foo = '  foo  '
console.log(foo.trimLeft())
//foo.trimStart() works neither
Run Code Online (Sandbox Code Playgroud)

我知道互联网上的大多数解决方案都说,我必须修复我的tsconfig.json以包含 es20whatever。

有趣的是,我可以使用 es2018 的东西,比如 Promise.prototype.finally 和 rest spread 等。VSCode 也会自动完成trimStart(),这很奇怪,因为项目和编辑器应该使用相同的tsconfig.json. 但是这段特定的代码无法编译。

这是我的 tsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "baseUrl": "./",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": ["node_modules/@types"],
    "lib": ["es2018", "dom"],
    "plugins": [
      {
        "name": "tslint-language-service",
        "configFile": "./tslint.json"
      }
    ],
    "paths": {
      "foo": ["projects/foo/src/public_api.ts"],
      "bar": ["projects/bar/src/public_api.ts"],
      "baz": ["dist/baz"]
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我在 monorepo 角度文件夹中运行它(如您所见)。也许这有问题,我不知道。

typescript tsc ecmascript-next

7
推荐指数
2
解决办法
4218
查看次数