Search code examples
javascriptnode.jses6-promise

Optimising a nested promise


How can I optimise the following (i.e. avoid nested promises)? It works but seems like I'm going to continue nesting promises

The code first authenticates and returns a service, then it feeds that service into a function that calls the api asynchronously to gets items, then I'll do something with the items after, probably calling another function containing an async call:

new Promise(function(resolve, reject) {
    auth.authenticate(resolve);
}).then(function(service) {
    console.log('service', service);
    new Promise(function(resolve, reject) {
        lineItems.getLineItems(service, resolve, reject);
    }).then(function(items) {
        console.log('returned line items');
        console.log(items);
    }).catch(function(err){
        console.log('error!', err);
    });
});

Solution

  • Just return the new promise from then:

    new Promise(function(resolve, reject) {
        auth.authenticate(resolve);
    }).then(function(service) {
        console.log('service', service);
        return new Promise(function(resolve, reject) {
            lineItems.getLineItems(service, resolve, reject);
        });
    }).then(function(items) {
        console.log('returned line items');
        console.log(items);
    }).catch(function(err){
        console.log('error!', err);
    });
    

    Also, if you can adjust lineItems.getLineItems to return a promise, it looks more concise:

    new Promise(function(resolve, reject) {
        auth.authenticate(resolve);
    }).then(function(service) {
        console.log('service', service);
        return lineItems.getLineItems(service);
    }).then(function(items) {
        console.log('returned line items');
        console.log(items);
    }).catch(function(err){
        console.log('error!', err);
    });