如何使用Nativecript与本机ES6 Promises [英] How to use Typescript with native ES6 Promises
问题描述
我是Typescript的完全初学者,我想知道是否可以在Typescript中使用ES6承诺以及我必须做些什么才能让它们起作用。我正在运行节点0.11.14并且在编译期间出现错误无法找到名称'承诺'
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'"
推荐答案
当前lib.d.ts中没有定义的promise,所以你需要一个额外的定义文件,这就是你得到编译错误的原因。
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.
你可以举个例子use(如@elclanrs所说)使用es6-promise包和DefinitelyTyped的定义文件: es6-promise定义
You could for example use (like @elclanrs says) use the es6-promise package with the definition file from DefinitelyTyped: es6-promise definition
您可以像这样使用它:
var p = new Promise<string>((resolve, reject) => {
resolve('a string');
});
编辑在定位ES6时,您可以在没有定义的情况下使用它(使用TypeScript编译器) - 注意你仍然需要Promise存在于运行时的课程中(因此它在旧的浏览器中不起作用:))
在 tsconfig.json中添加/编辑以下内容/ code>:
edit You 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
:
"compilerOptions": {
"target": "ES6"
}
编辑2
当TypeScript 2.0问世时事情会有所改变(尽管上面仍然有效)但定义文件可以直接用npm安装,如下所示:
edit 2 When 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:
npm install --save @ types / es6-promise
- 来源
edit3
使用更多信息更新答案以使用类型。
edit3 Updating answer with more info for using the types.
创建一个只有 {}
的 package.json
文件e内容(如果你还没有package.json。
致电 npm install --save @ types / es6-promise
和 tsc --init
。第一个npm install命令将更改 package.json
以包含es6-promise作为依赖项。 tsc --init会为你创建一个 tsconfig.json
文件。
Create a package.json
file with only { }
as the content (if you don't have a package.json already.
Call npm install --save @types/es6-promise
and tsc --init
. The first npm install command will change your package.json
to include the es6-promise as a dependency. tsc --init will create a tsconfig.json
file for you.
你现在可以使用你的承诺typescript文件 var x:Promise< any> ;;
。
执行 tsc -p。
来编译项目。你应该没有错误。
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.
这篇关于如何使用Nativecript与本机ES6 Promises的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!