Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
788 views
in Technique[技术] by (71.8m points)

how to use es6-promises with typescript?

I read this SO question but having trouble getting promises to work with typescript. Hopefully we can make a clear guide. This is for a server/node project. I'm actually using latest iojs, but targeting ES5 as output.

$ 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;
}

this is giving the error:

Cannot find name 'Promise'.

// alternatively:

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


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

What is the recommended way to return a Promise from your own node server side code?

references:

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...