Promises: Ember.RSVP is not a constructor

I am experimenting with Promises and trying to adapt a javascript Promise example I found to Ember. I’m getting this error in the console.

developer-sandbox.js:34 Uncaught TypeError: Ember.RSVP is not a constructor at DeveloperSandboxController.roll (developer-sandbox.js:34)

Here is what I have in my controller. I get the feeling I’m missing something important.

import Controller from '@ember/controller';
import { tracked } from "@glimmer/tracking";
import { action } from "@ember/object";
import Promise, { resolve, reject } from "rsvp";

export default class DeveloperSandboxController extends Controller {

...

    dieToss() {
        return Math.floor(Math.random() * 6) + 1;
    }

    @action
    roll() {
        console.log("One");

        let rollTheDie = new Promise(function(resolve, reject) {
            let n = this.dieToss();
            if (n === 6) {
                resolve(n);
            } else {
                reject(n);
            }
        });

        rollTheDie.then(function(toss) {
            console.log('Your rolled a ' + toss + '.');
        }, function(toss) {
            console.log('Unfortunately, you rolled a ' + toss + '.');
        });

        console.log("Two");
    }

UPDATE: If I don’t import Promise and move the function inside the action, it works. But, then I’m not using Ember, right?

Thanks for looking. Any help will be appreciated.

In spite of what the Ember docs seem to say (I just checked) I think you should import Promise as one of the destructured exports rather than the default export:

import { Promise, resolve, reject } from "rsvp";
1 Like

Thank you. That does clear up the error. But, if it works with or without the import, what do I gain by importing Promise?

My guess is that without the import you’re getting the native Promise and with the import you’re getting RSVPs Promise. For more reading on that subject see this nice explanation. It’s probably safe to just use the native Promise FWIW.

Thanks, again. I’ll read the explanation.

If you support IE you may not want to use native Promises based on the MDN page (I can never remember all the compatibility stuff).

1 Like

This will raise SonarLint Code smell. Any help here

Can you be more specific? What’s the issue? And what does the code look like?