Reputation: 367
So i brought to life this abomination and i couldnt for the life of me get my head around how to optimise it in such a way i can run this chain properly using Promise.all / Promise.join.
Anyone able to point me in the right direction? Should probably separate the methods first.
Any insight is appreciated.
getOpenIDConf: function() {
return client
.getAsync('openId')
.then(
function(result) {
if (!result) {
return request
.getAsync({
url: 'https://accounts.google.com/.well-known/openid-configuration',
json: true
}).spread(
function(response, body) {
var result = JSON
.stringify(body);
client.setAsync('openId',
result).then(
function() {
return result;
});
});
} else {
return result;
}
});
},
[EDIT] To clarify, i'm using bluebird
Upvotes: 0
Views: 76
Reputation: 3705
Refactoring a bit and changing the code style gives this.
getOpenIDConf: () => client.getAsync('openId').then(result =>
result || request.getAsync({
url: 'https://accounts.google.com/.well-known/openid-configuration',
json: true
}).get(1).then(JSON.stringify).then(result =>
client.setAsync('openId', result).return(result);
)
)
},
Upvotes: 2
Reputation: 84
A few features of a good promise library (not sure which one you are using) is that you can chain the promises like so:
doSomething(function(result) {
return doSomethingElse();
}).then(function(result2) {
return doSomethingElseAgain();
}).then(function(result3) {
// It all worked!
}).catch(function() {
// Something went wrong
});
Or you can wait for a set of them to complete:
var promiseArray = [];
promiseArray.push(doSomething());
promiseArray.push(doSomethingElse());
promiseArray.push(doSomethingElseAgain());
Promise.all(promiseArray).then(function() {
// It all worked!
}).catch(function() {
// Something went wrong
});
Hope this is informative.
Upvotes: 1