hendry
hendry

Reputation: 10813

Promises in several files

I'm struggling to organise a series of operations in Javascript as Promises (as opposed to a async waterfall), with each promise in a file so that I can test it on its own.

Working main.js, but "p1.p1()" is ugly!

p1 = require("./test.js");

console.log(p1)

p1.p1().then(function(val) {
  console.log(val); // 1
  return val + 2;
}).then(function(val) {
  console.log(val); // 3
})

test.js, in future I would want to have several {1..X}.js to import:

exports.p1 = function() { return new Promise(function(resolve, reject) { resolve(1); }); }

Is there a cleaner way to do this in Node 4.3?

Upvotes: 1

Views: 81

Answers (1)

Omar A
Omar A

Reputation: 445

If your only problem with p1.p1() is the repetition of p1 and you want to call it in a shorter manner, that in addition to your intention of having only one promise per file, then you can do as follows:

In test.js:

module.exports = function () {
    return new Promise( function (resolve, reject) {
        resolve(1)
    })
}

In main.js:

var p1 = require("./test.js")

p1()
    .then(function(p1_result) {
        console.log("Result of p1: ", p1_result)
    })
    .then(...)
    .catch(function(err) {
        // handle errors as you see fit in your case
    })
  • Beware that attaching the function returning the promise in test.js to module.exports will mean that you can only export that one function, but you did explicitly state that that is what you want to do.

PS: If you don't have to use Node v4.3, you should consider using a more recent version (6.9.x LTS, or 7.4.x current)

Upvotes: 1

Related Questions