Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

arrays - What is wrong with promise resolving?

Any ideas? Why does node say 'filename is undefined'? Thanks. Contract, policy ans invoice functions resolve with no data, just resolve().

var dc = function(data) {

return new Promise(function(resolve, reject) {

    var filename = 'Test';

    var contract = function() { ... }

    var policy = function() { ... }

    var invoice = function() { ... }

    contract().then(invoice().then(policy().then(function() {
        console.log(filename); // Test
        resolve(filename); // UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): ReferenceError: filename is not defined
    })))
})

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...