Search code examples
javascriptnode.jses6-promise

Chaining promises but with different parameters


I previously used callbacks for all my nodejs functions that need to access mysql or txt files. This lead to ugly code stacking the callbacks inside of each other so I converted them to promises. How can I chain the promises but with different parameters each time?

I know how to chain them with .then(), but I don't know how to pass different arguments each time.

app.get('/visual', function (request, response) {
    loadTextFile('tables', function (measureList) {
         loadTextFile('roles', function (roleList) {
              // Do something with roleList and measureList
         });
    });
});

This is how my code looked before with the callbacks, how can I convert them to use then()? (I know how to convert loadTextFile to a promise.)


Solution

  • As an another alternative to callback hells and Promise.then.then, You could also use async/await for that :

    const loadTextFile = file => new Promise( (resolve, reject) => {
          // Fetch the files etc.
          resolve(data);
    })
    
    const loadFiles = async (request, response) => {
      const measureList = await loadTextFile('tables');
      const roleList = await loadTextFile('roles');
    
      // Do something with roleList and measureList
    
      response.send(finalData);
    }
    
    app.get('/visual', loadFiles);