First of all, you cannot write:
contract().then(invoice() ... )
(that would work if the invoice()
function returned another function to act as a then
handler)
You have to write:
contract().then(function (value) { invoice() ... })
Or:
contract().then(value => invoice() ... )
Or maybe this if one function should handle the result of other function:
contract().then(invoice).then(policy).then(function (result) { ... });
What you have to pass as an argument to then
is a function, not a result of calling a function (which is probably a promise in your example).
I don't know if that's the only problem with your approach but it is certainly one of the problems. Of course it may work but probably not how you expect.
2017 Update
If you use ES2017 async/await that's available in Node since v7.0 then instead of:
contract().then(invoice).then(policy).then((result) => { ... });
you can use:
let a = await contract();
let b = await invoice(a);
let c = await policy(b);
// here your `result` is in `c`
or even this:
let result = await policy(await invoice(await contract()));
Note that you can only use it in functions declared with the async
keyword. This works on Node since version 7. For older versions of Node you can use a similar thing with a slightly different syntax using generator-based coroutines, or you can use Babel to transpile your code if that's what you prefer of if that what you already do.
This is quite a new feature but there are a lot of questions on Stack Overflow about it. See:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…