Search code examples
javascriptjquerypromiseecmascript-6es6-promise

ES2015 equivalent of $.Deferred()


I'm using Babel for a project, and I'm stuck with a very basic problem. I'm very used to jQuery's Deferred objects and I'm struggling to find its ES2015 equivalent, here is what I basically want:

// file1.js
let dfd = new Promise()

function functionCalledAtSomePoint(thing) {
    dfd.resolve(thing)
}

export default { dfd }


// file2.js
import { dfd } from './file1'

dfd.then((thing) => {
    console.log('Yay thing:', thing)
})

What should be the correct way to write this simple deferred?

EDIT with royhowie's answer:

// file1.js
let thing
function getThing(_thing) {
    return new Promise((resolve) => {
        if (el) {
            thing = new Thing(el)
        }
        resolve(thing)
    })
}

function functionCalledAtSomePoint(el) {
    getThing(el)
}

export default { getThing }


// file2.js
import { getThing } from './file1'

getThing.then((thing) => {
    console.log('Yay thing:', thing)
})

Solution

  • You can export the promise directly (instead of a function)—like you have—but then you'll only be able to use it (.then) once, which is probably not what you want.

    Instead, you should export a function which returns a Promise:

    file 1.js

    import User from '../models/user'
    
    export function getUsersFromDatabase () {
        return new Promise((resolve, reject) => {
            User.find({}, (err, users) => {
                return err ? reject(err) : resolve(users)
            })
        })
    }
    

    file2.js

    import { getUsersFromDatabase } from './file1'
    
    getUsersFromDatabase().then((users) => {
        // success
    }).catch((err) => {
        // no users
    })
    

    You can use the default Promise implementation, but it much slower than 3rd party modules, e.g., bluebird (which I very much recommend using).