user3742929
user3742929

Reputation: 400

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.)

Upvotes: 0

Views: 61

Answers (4)

Jeremy Thille
Jeremy Thille

Reputation: 26360

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);

Upvotes: 2

Asaf Aviv
Asaf Aviv

Reputation: 11760

As everybody else already said you should use async / await since the readability is superior to Promises / callbacks but i wanted to add that if your Promises doesn't depend on each other you can actually request them both simultaneity instead of waiting for one to finish before firing the next request using Promise.all

const loadTextFile = file => new Promise((resolve, reject) => {
  const fileData = getFileData(file);
  resolve(data);
}

const loadFiles = async () => {
  const [measureList, roleList] = await Promise.all([
    loadTextFile('tables'),
    loadTextFile('roles')
  ]);
};

Upvotes: 1

mandaputtra
mandaputtra

Reputation: 1070

If what do you mean is like this :

function multiply(a) {
  return new Promise((resolve, reject) => {
    resolve(a * a)
  })
}

function promise1() {
  return new Promise((resolve, reject) => {
    resolve(5)
  })
}

promise1.then(add).then(res => console.log(res))

then the answer is yes.

Upvotes: 0

Nicolae Maties
Nicolae Maties

Reputation: 2655

Start using async - await:

async function loadFiles() {
    const loadTextFilesTables = await loadTextFile('tables', measureList);
    const loadTextFilesRoles = await loadTextFile('roles', roleList);
    //...
}

Upvotes: 2

Related Questions