Search code examples
javascriptpromisebluebird

Promises Good Practice


Quick question.

For a complex Promise function, is it better to organize your code like this:

One unique function with the smallest functions possible next to each oher

var a = () => {
    return new Promise((resolve, reject) => {
        return promise1().then((result1) => {
            return promise2(result1)
        }).then((result2) => {
            return promise3(result2)
        }).then((result3) => {
            return promise4(result3)
        }).then((result4) => {
            resolve(result4)
        }).catch((error) => {
            reject(error)
    })
}

or like this

Encapsulate some of the complexity into other functions to have a simpler high level function.

var b = () => {
    return new Promise((resolve, reject) => {
        return promise12().then((result12) => {
            return promise34(result12)
        }).then((result4) => {
            resolve(result4)
        }).catch((error) => {
            reject(error)
        })
    })
}

var promise12 = () => {
    return new Promise ((resolve, reject) => {
        return promise1().then((result1) => {
            return promise2(result1)
        }).then((result2) => {
            resolve(result2)
        }).catch((error) => {
            reject(error)
        })
    })
}

var promise34 = (result2) => {
    return new Promise ((resolve, reject) => {
        return promise3().then((result3) => {
            return promise4(result4)
        }).then((result) => {
            resolve(result4)
        }).catch((error) => {
            reject(error)
        })
    })
}

Solution

  • There's no "best way" to organize your code. You should consider separating your functions into logical modules, so that their usage is "intuitive".

    Also, you haven't mentioned generators (functions with * next to them), which is a new javascript ES6 feature. Very likely that in the future these generator function will be a 'de facto' way to handle asynchronous code, because they are well designed to handle it. They are also easy to read and test. You can watch this (currently) free course by Max Stoiber to learn more about them. This course is specifically designed to show how you can write asynchronous code with generator functions.