I'm trying to understand promises better by using them in a hobby project, but I don't understand why it's taking the value from the first .then
of the promise chain instead of the last one. In other words, how would I run some arbitrary code in a promise, then at the end, return a value to the outside of that promise? Thanks! I expect the value 'x' but the program returns 'b'.
var Promise = require('bluebird')
Promise.resolve('x')
.then(function (user) {
return Promise.resolve('c').then(function (roll) {
return Promise.resolve('a').then(function (user) {
return Promise.resolve('b')
})
.then(Promise.resolve('x'))
})
})
.then(function (output) {
console.log(output)
})
I believe that a promise can only be resolved once. The rest will be ignored. Further mutation of the resolved value is achieved by chaining then
s. To achieve the results you are looking for (output of x
), your code would be:
var Promise = require('bluebird')
Promise.resolve('x')
.then(function (doesnotmatter) {
return Promise.resolve('c').then(function (alsodoesnotmatter) {
return Promise.resolve('a').then(function (noneofthismatters) {
return Promise.resolve('b')
})
.then(function(){return 'x'})
})
})
.then(function (output) {
console.log(output) // 'x'
})
To make the example more clear:
var Promise = require('bluebird')
Promise.resolve('y')
.then(function (y) {
// y == 'y'
return 'c';
})
.then(function(c) {
// c == 'c'
return 'a';
})
.then(function(a) {
// a == 'a'
return 'b';
})
.then(function(b) {
// b == 'b'
return 'x';
}).
then(function(x) {
console.log(x); // output is 'x';
});