简体   繁体   English

链接承诺,但参数不同

[英]Chaining promises but with different parameters

I previously used callbacks for all my nodejs functions that need to access mysql or txt files. 以前,我为需要访问mysql或txt文件的所有nodejs函数使用了回调。 This lead to ugly code stacking the callbacks inside of each other so I converted them to promises. 这导致丑陋的代码将回调相互堆叠在一起,因此我将它们转换为Promise。 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. 我知道如何用.then()链接它们,但我不知道每次都传递不同的参数。

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() ? 这是我的代码在使用回调之前的样子,如何将它们转换为使用then() (I know how to convert loadTextFile to a promise.) (我知道如何将loadTextFile转换为Promise。)

Start using async - await : 开始使用async - await

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

As an another alternative to callback hells and Promise.then.then , You could also use async/await for that : 作为回调地狱和Promise.then.then的另一种选择,您还可以使用async / await:

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

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 正如其他人已经说过的那样,您应该使用async / await,因为可读性优于Promises /回调,但是我想补充一点,如果Promises彼此不依赖,则可以同时要求它们同时执行,而不是等待它们完成在使用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')
  ]);
};

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. 那么答案是肯定的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM