promise.all

  1. const fs = require('fs');
  2. function readFile(filePath) {
  3. return new Promise((resolve, reject) => {
  4. fs.readFile(filePath, (err, data) => {
  5. if (err) {
  6. return reject(err)
  7. }
  8. resolve(data)
  9. })
  10. })
  11. }
  12. /*
  13. * Promise.all方法接收一个数组参数,数组中是一个个的promise对象,
  14. * 该方法的返回值也是一个promise对象
  15. *
  16. * */
  17. Promise.all([
  18. readFile('./a.txt'),
  19. readFile('./b.txt'),
  20. readFile('.c.txt')
  21. ]).then(data=>{
  22. console.log(data[0].toString());
  23. console.log(data[1].toString());
  24. console.log(data[2].toString());
  25. }).catch((err)=>{
  26. console.log(err);
  27. });




原文地址:https://www.cnblogs.com/itlyh/p/6041073.html