how to use es6-promises with typescript?

守給你的承諾、 提交于 2019-11-28 09:34:59

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

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

I was able to use Promises with async/await by installing es6-promise and then adding this to the top of the file:

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

And this to tsconfig.json

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

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

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:

import { polyfill } from 'es6-promise'

polyfill();

Add the following to package.json:

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

Change target to "es6" in your tsconfig.json

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

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!