Javascript 如何在原生 ES6 Promise 中使用 Typescript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27573365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:20:33  来源:igfitidea点击:

How to use Typescript with native ES6 Promises

javascripttypescriptes6-promise

提问by dchang

I'm a complete beginner to Typescript and am wondering if it's possible to use ES6 promises in Typescript and what I would have to do to get them to work. I'm running node 0.11.14 and am getting an error during compilation "Cannot find name 'Promise'"

我是一个完整的 Typescript 初学者,想知道是否可以在 Typescript 中使用 ES6 承诺,以及我必须做些什么才能让它们工作。我正在运行节点 0.11.14 并且在编译过程中出现错误“找不到名称 'Promise'”

回答by Dick van den Brink

The current lib.d.ts doesn't have promises in it defined so you need a extra definition file for it that is why you are getting compilation errors.

当前的 lib.d.ts 中没有定义 promise,因此您需要一个额外的定义文件,这就是为什么会出现编译错误的原因。

You could for example use (like @elclanrs says) use the es6-promise package with the definition file from DefinitelyTyped: es6-promise definition

例如,您可以使用(如@elclanrs 所说)将 es6-promise 包与来自绝对类型的定义文件一起使用:es6-promise 定义

You can then use it like this:

然后你可以像这样使用它:

var p = new Promise<string>((resolve, reject) => { 
    resolve('a string'); 
});

editYou can use it without a definition when targeting ES6 (with the TypeScript compiler) - Note you still require the Promise to exists in the runtime ofcourse (so it won't work in old browsers :)) Add/Edit the following to your tsconfig.json:

编辑您可以在面向 ES6(使用 TypeScript 编译器)时在没有定义的情况下使用它 - 请注意,您仍然需要 Promise 存在于当然的运行时中(因此它在旧浏览器中不起作用:))将以下内容添加/编辑到您的tsconfig.json

"compilerOptions": {
    "target": "ES6"
}

edit 2When TypeScript 2.0 will come out things will change a bit (though above still works) but definition files can be installed directly with npm like below:

编辑 2当 TypeScript 2.0 出来时,事情会有所改变(虽然上面仍然有效)但定义文件可以直接使用 npm 安装,如下所示:

npm install --save @types/es6-promise- source

npm install --save @types/es6-promise-来源

edit3Updating answer with more info for using the types.

edit3使用更多信息更新答案以使用这些类型。

Create a package.jsonfile with only { }as the content (if you don't have a package.json already. Call npm install --save @types/es6-promiseand tsc --init. The first npm install command will change your package.jsonto include the es6-promise as a dependency. tsc --init will create a tsconfig.jsonfile for you.

创建一个package.json{ }作为内容的文件(如果你还没有 package.json。调用npm install --save @types/es6-promisetsc --init。第一个 npm install 命令将改变你package.json的包含 es6-promise 作为依赖项。tsc --init 将创建一个tsconfig.json文件为你。

You can now use the promise in your typescript file var x: Promise<any>;. Execute tsc -p .to compile your project. You should have no errors.

您现在可以在打字稿文件中使用承诺var x: Promise<any>;。执行tsc -p .以编译您的项目。你应该没有错误。

回答by Shaun Luttin

Alternative #1

替代方案#1

Use the targetand libcompiler options to compile directly to es5without needing to install the es6-shim. (Tested with TypeScript 2.1.4). In the lib section, use either es2016or es2015.promise.

使用targetlib编译器选项直接编译,es5无需安装es6-shim. (用 TypeScript 测试2.1.4)。在 lib 部分中,使用es2016es2015.promise

// tsconfig.json
{
    "compilerOptions": {
        "target": "es5",
        "lib": [
            "es2015.promise",
            "dom"
        ]
    },
    "include": [
        "src/**/*.ts"
    ],
    "exclude": [
        "node_modules"
    ]
}

Alternative #2

替代方案#2

Use NPM to installthe es6-shimfrom the types organization.

使用NPM安装es6-shim组织类型

npm install @types/es6-shim --save-dev

Alternative #3

替代方案 #3

Before TypeScript 2.0, use typingsto install the es6-shimglobally from DefinitelyTyped.

在 TypeScript 2.0 之前,使用typings来安装es6-shim来自绝对类型的全局。

npm install typings --global --save-dev
typings install dt~es6-shim --global --save-dev

The typingsoption uses npmto install typingsglobally and then uses typingsto install the shim. The dt~prefix means to download the shim from DefinitelyTyped. The --globaloption means that the shim's types will be available throughout the project.

typings选项用于全局npm安装typings,然后用于typings安装 shim。该dt~前缀是指从DefinitelyTyped下载垫片。该--global选项意味着垫片的类型将在整个项目中可用。

See also

也可以看看

https://github.com/Microsoft/TypeScript/issues/7788- Cannot find name 'Promise' & Cannot find name 'require'

https://github.com/Microsoft/TypeScript/issues/7788- 找不到名称 'Promise' 和找不到名称 'require'

回答by paldepind

As of TypeScript 2.0 you can include typings for native promises by including the following in your tsconfig.json

从 TypeScript 2.0 开始,您可以通过在您的 tsconfig.json

"compilerOptions": {
    "lib": ["es5", "es2015.promise"]
}

This will include the promise declarations that comes with TypeScript without having to set the target to ES6.

这将包括 TypeScript 附带的承诺声明,而无需将目标设置为 ES6。

回答by Plantain Yao

If you use node.js 0.12 or above / typescript 1.4 or above, just add compiler options like:

如果您使用 node.js 0.12 或更高版本 / typescript 1.4 或更高版本,只需添加编译器选项,例如:

tsc a.ts --target es6 --module commonjs

More info: https://github.com/Microsoft/TypeScript/wiki/Compiler-Options

更多信息:https: //github.com/Microsoft/TypeScript/wiki/Compiler-Options

If you use tsconfig.json, then like this:

如果你使用tsconfig.json,那么像这样:

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es6"
    }
}

More info: https://github.com/Microsoft/TypeScript/wiki/tsconfig.json

更多信息:https: //github.com/Microsoft/TypeScript/wiki/tsconfig.json

回答by Nick Kenens

This the most recent way to do this, the above answer is outdated:

这是最近的方法,上面的答案已经过时了:

typings install --global es6-promise

typings install --global es6-promise

回答by Bibek Bhattacharya

Using native ES6 Promises with Typescript in Visual Studio 2015 + Node.js tools 1.2

在 Visual Studio 2015 + Node.js 工具 1.2 中使用带有 Typescript 的原生 ES6 Promises

No npm install required as ES6 Promises is native.

不需要 npm install 因为 ES6 Promises 是原生的。

Node.js project-> Properties -> Typescript Build tab ECMAScript version = ECMAScript6

Node.js 项目-> 属性 -> Typescript 构建选项卡 ECMAScript 版本 = ECMAScript6

import http = require('http');
import fs = require('fs');

function findFolderAsync(directory : string): Promise<string> {

    let p = new Promise<string>(function (resolve, reject) {

        fs.stat(directory, function (err, stats) {

            //Check if error defined and the error code is "not exists"
            if (err && err.code === "ENOENT") {
                reject("Directory does not exist");
            }
            else {
                resolve("Directory exists");
            }
        });

    });
    return p;
}

findFolderAsync("myFolder").then(

    function (msg : string) {
        console.log("Promise resolved as " + msg); 
    },
    function (msg : string) {
        console.log("Promise rejected as " + msg); 
    }
);

回答by Vaz

A. If using "target": "es5"and TypeScript version below 2.0:

A. 如果使用"target": "es5"TypeScript 版本低于 2.0:

typings install es6-promise --save --global --source dt

B. If using "target": "es5"and TypeScript version 2.0 or higer:

B. 如果使用"target": "es5"TypeScript 2.0 或更高版本:

"compilerOptions": {
    "lib": ["es5", "es2015.promise"]
}

C. If using "target": "es6", there's no need to do anything.

C. 如果使用"target": "es6",则无需执行任何操作。

回答by James

I had to downgrade @types/core-jsto 9.36 to get it to work with "target": "es5"set in my tsconfig.

我不得不降级@types/core-js到 9.36 才能让它"target": "es5"在我的 tsconfig 中使用set。

"@types/core-js": "0.9.36",

"@types/core-js": "0.9.36",