khoa-pham-async-await

Promise liên tục


1. Nhắc lại tái sử dụng Promise

const fs = require('fs');
let promiseRead = (path) => {
  return new Promise((resolve, reject) => {
    fs.readFile(path, { encoding: 'utf-8' }, (err, data) => {
      if (err) {
        return reject(new Error('Kiểm tra lại đường dẫn!') + '');
      }
      return resolve(data);
    });
  });
};
promiseRead('../docs/test1.txt').then(
  (res) => console.log(res),
  (err) => console.log(err)
);
let add = (a, b) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (typeof a != 'number' || typeof b != 'number') {
        return reject(new Error('Tham số truyền vào phải là kiểu number!'));
      }
      resolve(a + b);
    }, 1000);
  });
};

add(4, 5).then(
  (res) => console.log(res),
  (err) => console.log(err + '')
);

2. Sử dụng Promise liên tiếp nhau để xử lý Callback Hell

// Phép tính cộng
let add = (a, b) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (typeof a != 'number' || typeof b != 'number') {
        return reject(new Error('Tham số truyền vào phải là kiểu number!'));
      }
      return resolve(a + b);
    }, 1000);
  });
};

// (4 + 5)
add(4, 5).then(
  (data) => console.log(data),
  (err) => console.log(err + '')
);
// (4 + 5) + 6
add(4, 5).then(
  (data) =>
    add(data, 6).then(
      (data2) => console.log(data2),
      (err2) => console.log(err2 + '')
    ),
  (err) => console.log(err + '')
);

Promise liên tục

// (4 + 5) + 6
add(4, 5)
  .then(
    (data) => add(data, 6),
    (err) => console.log(err + '')
  )
  .then(
    (data2) => console.log(data2),
    (err2) => console.log(err2 + '')
  );
// (4 + 5) + 6
add(4, '5')
  .then(
    (data) => add(data, 6),
    (err) => console.log(err + '')
  )
  .then(
    (result) => console.log('Kết quả là: ', result),
    (err2) => console.log(err2 + '')
  );

Promise liên tục

// (4 + 5) + 6
add(4, '5')
  .then((data) => add(data, 6))
  .then((result) => console.log('Kết quả là: ', result))
  .catch((error) => console.log(error + ''));

Promise catch Error

3. Áp dụng Promise liên tiếp nhau để xử lý tính diện tích hình thang

// Phép Cộng
let add = (a, b, callBack) => {
  setTimeout(() => {
    if ((typeof a != 'number') | (typeof b != 'number')) {
      return callBack(new Error('Tham so phai có kieu number.'));
    }
    return callBack(undefined, a + b);
  }, 1000);
};

// Phép Nhân
let multiply = (a, b, callBack) => {
  setTimeout(() => {
    if ((typeof a != 'number') | (typeof b != 'number')) {
      return callBack(new Error('Tham so phai có kieu number.'));
    }
    return callBack(undefined, a * b);
  }, 1000);
};

// Phép Chia
let divide = (a, b, callBack) => {
  setTimeout(() => {
    if ((typeof a != 'number') | (typeof b != 'number')) {
      return callBack(new Error('Tham so phai có kieu number.'));
    }
    if (b == 0) {
      return callBack(new Error('So bi chia phai khac 0.'));
    }
    return callBack(undefined, a / b);
  }, 1000);
};

// Tính Diện tích hình thang

let square = (a, b, c, cb) => {
  add(a, b, (err1, res1) => {
    if (err1) return cb(err1);
    multiply(res1, c, (err2, res2) => {
      if (err2) return cb(err2);
      divide(res2, 2, (err3, res3) => {
        if (err3) return cb(err3);
        return cb(undefined, res3);
      });
    });
  });
};

// Diện tích hình thang
square(2, 3, `2`, (err, res) => {
  if (err) {
    return console.log(err + '');
  }
  console.log('Dien tich: ' + res);
});
let add = (a, b) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (typeof a != 'number' || typeof b != 'number') {
        return reject(new Error('Tham số truyền vào phải là kiểu number!'));
      }
      return resolve(a + b);
    }, 1000);
  });
};

let multiply = (a, b) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (typeof a != 'number' || typeof b != 'number') {
        return reject(new Error('Tham số truyền vào phải là kiểu number!'));
      }
      return resolve(a * b);
    }, 1000);
  });
};

let divide = (a, b) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (typeof a != 'number' || typeof b != 'number') {
        return reject(new Error('Tham số truyền vào phải là kiểu number!'));
      }
      if (b === 0) {
        return reject(new Error('Số chia phải khác 0.'));
      }
      return resolve(a / b);
    }, 1000);
  });
};

let square = (a, b, h) => {
  add(a, b)
    .then((res) => multiply(res, h))
    .then((res) => divide(res, 2))
    .then((res) => console.log('Diện tích hình thang: ' + res))
    .catch((err) => console.log(err + ''));
};

square(4, 6, 5);

Cụ thể là đoạn:

// Tính Diện tích hình thang

let square = (a, b, c, cb) => {
  add(a, b, (err1, res1) => {
    if (err1) return cb(err1);
    multiply(res1, c, (err2, res2) => {
      if (err2) return cb(err2);
      divide(res2, 2, (err3, res3) => {
        if (err3) return cb(err3);
        return cb(undefined, res3);
      });
    });
  });
};

// Diện tích hình thang
square(2, 3, `2`, (err, res) => {
  if (err) {
    return console.log(err + '');
  }
  console.log('Dien tich: ' + res);
});
let square = (a, b, h) => {
  add(a, b)
    .then((res) => multiply(res, h))
    .then((res) => divide(res, 2))
    .then((res) => console.log('Diện tích hình thang: ' + res))
    .catch((err) => console.log(err + ''));
};

square(4, 6, 5);
let square = (a, b, h) => {
  return add(a, b)
    .then((res) => multiply(res, h))
    .then((res) => divide(res, 2));
};

square(4, 5, 6)
  .then((res) => console.log('Diện tích hình thang: ' + res))
  .catch((err) => console.log(err + ''));

Promise catch Error

4.Tóm tắt