2015-09-05 59 views
40

我讀this SO question,但很難得到使用打字稿的承諾。希望我們能夠做出明確的指導。 這是用於服務器/節點項目。我實際上使用最新的iojs,但將ES5作爲輸出。如何使用es6-promises與打字稿?

$ tsd query es6-promise --action install --save 
$ npm install --save es6-promise 


// typescript code: 

/// <reference path="../../typings/es6-promise/es6-promise.d.ts"/> 

var Promise = require("es6-promise").Promise; 
require('es6-promise').polyfill(); 

function test():Promise { 
    var p:Promise = new Promise(); 
    return p; 
} 

這是給錯誤:

Cannot find name 'Promise'. 

//或者:

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


//error=> Untyped function calls may not accept type arguments. 

什麼是從你自己的節點服務器端代碼返回無極推薦的方法是什麼?

引用:

回答

45

main.ts

import {Promise} from 'es6-promise'; 
const p: Promise<string> = new Promise (
    (resolve: (str: string)=>void, reject: (str: string)=>void) => { 
     const a: string = "hello from Promise"; 
     resolve(a); 
    } 
); 
p.then((st) => { 
    console.log(st); 
}); 

tsconfig.json

{ 
    "compilerOptions": { 
     "target": "es3", 
     "module": "commonjs", 
     "declaration": false, 
     "noImplicitAny": false, 
     "noLib": false 
    }, 
    "filesGlob": [ 
     "./**/*.ts", 
     "!./node_modules/**/*.ts" 
    ], 
    "files": [ 
     "./main.ts", 
     "./typings/es6-promise/es6-promise.d.ts" 
    ] 
} 

compileandrun.sh

#!/bin/sh 
npm install es6-promise 
tsd install es6-promise 
tsc 
node main.js 
+0

非常詳細的答案,非常感謝! – dcsan

+2

現在推薦使用'typings'而不是'tsd'嗎? –

+5

注意那些使用Angular 2的人:你不需要(也不應該使用)import {Promise}語句,你不需要es6-promise.d.ts,因爲它與Angular 2框架捆綁在一起(as無論如何,beta 15都是)。 –

10

以下是在V2.1.1 +設置爲es5

我能夠通過安裝es6-promise,然後加入這個使用與async/await承諾目標到文件頂部:

global.Promise = require('es6-promise').Promise; 

而這到tsconfig.json

"lib": [ "es2015.promise", "es5" ], 

使用import { Promise }形式對我來說其他文庫崩潰沒有工作(例如:Axios公司)

1

以下內容添加到package.json

"devDependencies": { 
"@types/es6-promise": "^0.0.32" 
}, 
"dependencies": { 
"es6-promise": "~4.1.0" 
} 
+0

如果我這樣做,是否需要導入'Promise'或者我可以使用它嗎? ? –

3

我需要填充工具這在不同的框架(具體而言,愛可信);我不需要真正創造我自己的承諾,所以這些解決方案都不適合我。幸運的是,答案很簡單,如果隱藏得很好:

import { polyfill } from 'es6-promise' 

polyfill(); 
+0

超級遲到的迴應,但我只是想提醒你,你自己是我的前往方法。 TS 2.7.2沒有其他框架(例如,沒有Angular),es6承諾,然後'polyfill()'是支持IE11的最簡單的方式。 謝謝。 – mschofield