typescript 如何在打字稿中使用 es6-promises?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32408306/
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-09-09 06:47:23  来源:igfitidea点击:

how to use es6-promises with typescript?

typescriptes6-promise

提问by dcsan

I read this SO questionbut 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.

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

$ 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?

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

references:

参考:

回答by Ilya Kharlamov

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

编译运行.sh

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

回答by BrunoLM

The following was on v2.1.1+ with the target set to es5

以下是在 v2.1.1+ 上,目标设置为 es5

I was able to use Promises with async/awaitby installing es6-promiseand then adding this to the top of the file:

我可以async/await通过安装es6-promise然后将其添加到文件顶部来使用 Promises :

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

And this to tsconfig.json

而这对 tsconfig.json

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


Using the import { Promise }form did not work for me as other libraries were crashing (ex: axios)

使用该import { Promise }表单对我不起作用,因为其他库崩溃了(例如:axios)

回答by bvoyelr

I needed to polyfill this in for a different framework (specifically, axios); I didn't need to actually create my own promises, so none of these solutions worked for me. Fortunately, the answer was simple, if well-hidden:

我需要为不同的框架(特别是 axios)填充它;我不需要实际创建自己的承诺,所以这些解决方案都不适合我。幸运的是,答案很简单,如果隐藏得很好:

import { polyfill } from 'es6-promise'

polyfill();

回答by Luis Cantero

Add the following to package.json:

将以下内容添加到package.json

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

回答by cancerbero

You don't need to install any library to use promises, async/await and the rest of the new stuff and target es5. just make sure you include a lib version that supports promises, in general I use esnext - you could be more cautious..

你不需要安装任何库来使用 promises、async/await 和其他新东西和目标 es5。只要确保你包含一个支持 promises 的 lib 版本,通常我使用 esnext - 你可以更谨慎..

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "lib": ["esnext", "dom"], 
    "strict": true, 
    "esModuleInterop": true,
    "sourceMap": true,
    "outDir": "./dist", 
    "rootDir": ".",
  },
  "include": ["src"]
}

and voila, use promises and async await also:

瞧,还使用 ​​promises 和 async await:

async function f(url:string){
    const response = await fetch(url)
    var data = await decodeOrThrow(await response.arrayBuffer())
}

回答by Jie Wang

Change target to "es6" in your tsconfig.json

在 tsconfig.json 中将目标更改为“es6”

"compilerOptions": {"target": "es6" }

Or install TypeScript for Visual Studio 2015 can also solve this problem without modify tsconfig.json

或者安装 TypeScript for Visual Studio 2015 也可以解决这个问题,无需修改 tsconfig.json

https://www.microsoft.com/en-us/download/details.aspx?id=48593

https://www.microsoft.com/en-us/download/details.aspx?id=48593