Reputation: 1818
I'm trying to figure the concept of promises in javascript.
I've looked at this code:
new Promise(function(res,rej) {
res("aaa");
})
.then(function(result) {
console.log(result);
return "bbb";
})
.then(function(result) {
console.log(result);
return "ccc";
})
.then(function(result) {
console.log(result);
});
it prints:
aaa
bbb
ccc
to the console log.
a few questions:
is the then()
method 1'st parameter is a function that will be run as the resolve()
method?
is the then()
method also returns a value which is a promise and this promise is the same promise as the one it is linked to (its parent) only the value of its resolve()
method is the value return from the resolve()
method inside the then()
?
is this promise:
var myPromise = new Promise(function(res,rej) {
res("aaa");
})
.then(function(result) {
console.log(result);
return "bbb";
})
is equivalents to this promise below?
var myPromise = new Promise(function(res,rej) {
res("bbb");
})
in addition, what is happening when the then()
accepts a promise?
like in this example?
var firstMethod = function() {
var promise = new Promise(function(resolve, reject){
setTimeout(function() {
console.log('first method completed');
resolve({data: '123'});
}, 2000);
});
return promise;
};
var secondMethod = function(someStuff) {
var promise = new Promise(function(resolve, reject){
setTimeout(function() {
console.log('second method completed');
resolve({newData: someStuff.data + ' some more data'});
}, 2000);
});
return promise;
};
var thirdMethod = function(someStuff) {
var promise = new Promise(function(resolve, reject){
setTimeout(function() {
console.log('third method completed');
resolve({result: someStuff.newData});
}, 3000);
});
return promise;
};
firstMethod()
.then(secondMethod)
.then(thirdMethod);
Upvotes: 0
Views: 475
Reputation: 29846
var resolvedPromise = new Promise(function(res,rej){ res({data: 7}) });
var rejectedPromise = new Promise(function(res,rej){ rej('error!!!!') });
resolvedPromise.then(function(res){ console.log('resolved:' + JSON.stringify(res)); }, function (err){ console.log('rejected:' + err); });
rejectedPromise.then(function(res){ console.log('resolved:' + JSON.stringify(res)); }, function (err){ console.log('rejected:' + err); });
var promise = new Promise(function(res,rej){ res({data: 7}) });
promise.
then(function(res){ console.log(res); return res.data; }).
then(function(res){ console.log(res); return res + 1; }).
then(function(res){ console.log(res);});
Upvotes: 3