1

On Node.js, what is the proper way to use promises with TypeScript ?

Currently I use a definition file "rsvp.d.ts":

interface Thenable {
    then(cb1: Function, cb2?: Function): Thenable;
}
declare module rsvp {
    class Promise implements Thenable {
        static cast(p: Promise): Promise;
        static cast(object?): Promise;
        static resolve(t: Thenable): Promise;
        static resolve(obj?): Promise;
        static reject(error?: any): Promise;
        static all(p: Promise[]): Promise;
        static race(p: Promise[]): Promise;
        constructor(cb: Function);
        then(cb1: Function, cb2?: Function): Thenable;
        catch(onReject?: (error: any) => Thenable): Promise;
        catch(onReject?: Function): Promise;
    }
}

… and in my ".ts" file:

/// <reference path='../node.d.ts' />
/// <reference path='rsvp.d.ts' />
global['rsvp'] = require('es6-promise');
var Promise = rsvp.Promise;
var p: Thenable = new Promise(function (resolve) {
    console.log('test');
    resolve();
});

It works but the reference to "global" is ugly.

NB. I failed to use the definition file from DefinitelyTyped.

Paleo
  • 21,831
  • 4
  • 65
  • 76

1 Answers1

1

Proper fix

Just updated the definitions to support the correct way : https://github.com/borisyankov/DefinitelyTyped/pull/2430

So using the same defs (https://github.com/borisyankov/DefinitelyTyped/tree/master/es6-promises) now you can do:

import rsvp = require('es6-promises');
var Promise = rsvp.Promise;

Just a suggestion for future

It works but the reference to "global" is ugly.

You can do :

var rsvp = require('es6-promise');
var Promise = rsvp.Promise;
basarat
  • 261,912
  • 58
  • 460
  • 511
  • Thank you. About the suggestion, tsc was OK but WebStorm reported (by mistake) an error. – Paleo Jun 29 '14 at 10:15