如何在打字稿中使用es6-promises? [英] how to use es6-promises with typescript?

查看:52
本文介绍了如何在打字稿中使用es6-promises?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了此SO问题,但遇到问题承诺使用打字稿。希望我们能做出明确的指导。
这是用于服务器/节点项目。我实际上使用的是最新的iojs,但是将ES5作为输出。

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

这给出了错误:

Cannot find name 'Promise'.

//或者:

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


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

从您自己的节点服务器端代码返回Promise的推荐方法是什么?

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

引用:

https://github.com /borisyankov/DefinitelyTyped/blob/master/es6-promise/es6-promise-commonjs-tests.ts

推荐答案

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

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

compileandrun.sh

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

这篇关于如何在打字稿中使用es6-promises?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆