SoFunction
Updated on 2025-03-03

Analysis of application examples of ES6 Promise object

This article describes the application of ES6 Promise objects. Share it for your reference, as follows:

The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.

The Promise object is used to represent the final completion (or failure) of an asynchronous operation and its result value. To put it simply, it is used to handle asynchronous operations. If the asynchronous processing is successful, it will execute a successful operation. If the asynchronous processing fails, it will catch an error or stop subsequent operations.

How to handle asynchronous callbacks before promise

function asyncFun(a,b,callback) {
   setTimeout(function () {
    callback(a+b);
   },200);
  }
  asyncFun(1,2, function (res) {
   if(res > 2) {
    asyncFun(res, 2, function (res) {
     if(res > 4) {
      asyncFun(res, 2, function (res) {
       ('ok');
       (res);
      })
     }
    })
   }
  });

From the above, we can see the horror of the so-called "callback hell"

Use promise to handle asynchronous gracefully

function asyncFun(a,b) {
 return new Promise(function (resolve, reject) {
  setTimeout(function() {
   resolve(a + b);
  },200);
 })
}
asyncFun(1,2)
.then(function (res) {
 if(res > 2) {
  return asyncFun(res, 2);
 }
})
.then(function (res) {
 if(res > 4) {
  return asyncFun(res, 2);
 }
})
.then(function (res) {
 ('ok');
 (res);
})
.catch(function (error) {
 (error);
});

Example of using promise to handle internal exceptions

function asyncFun(a,b) {
 return new Promise(function (resolve, reject) {
  // Simulate exception judgment  if(typeof a !== 'number' || typeof b !== 'number') {
   reject(new Error('no number'));
  }
  setTimeout(function() {
   resolve(a + b);
  },200);
 })
}
asyncFun(1,2)
.then(function (res) {
 if(res > 2) {
  return asyncFun(res, 2);
 }
},function (err) {
 ('first err: ', err);
})
.then(function (res) {
 if(res > 4) {
  return asyncFun(res, 'a');
 }
},function (err) {
 ('second err: ', err);
})
.then(function (res) {
 ('ok');
 (res);
},function (err) {
 ('third err: ', err);
});

From the above, we can see that the exception in the promise object is handled through the second callback function of then, and the exception promise object is returned by reject

Unified error handling through catch, and finally the logic that must be executed is finally executed

function asyncFun(a,b) {
 return new Promise(function (resolve, reject) {
  // Simulate exception judgment  if(typeof a !== 'number' || typeof b !== 'number') {
   reject(new Error('no number'));
  }
  setTimeout(function() {
   resolve(a + b);
  },200);
 })
}
asyncFun(1,2)
.then(function (res) {
 if(res > 2) {
  return asyncFun(res, 2);
 }
})
.then(function (res) {
 if(res > 4) {
  return asyncFun(res, 'a');
 }
})
.then(function (res) {
 ('ok');
 (res);
})
.catch(function (error) {
 ('catch: ', error);
})
.finally(function () {
 ('finally: ', 1+2);
});

Handle multiple asynchronous methods through () static method

function asyncFun(a,b) {
 return new Promise(function (resolve, reject) {
  setTimeout(function() {
   resolve(a + b);
  },200);
 })
}
var promise = ([asyncFun(1,2), asyncFun(2,3), asyncFun(3,4)])
(function (res) {
 (res); // [3, 5, 7]
});

Use the () static method to get the fastest one among multiple asynchronous

function asyncFun(a,b,time) {
 return new Promise(function (resolve, reject) {
  setTimeout(function() {
   resolve(a + b);
  },time);
 })
}
var promise = ([asyncFun(1,2,10), asyncFun(2,3,6), asyncFun(3,4,200)])
(function (res) {
 (res); // 5
});

Directly return successful asynchronous object through the () static method

var p = ('hello');
(function (res) {
 (res); // hello
});

Equivalent to, as follows:

var p = new Promise(function (resolve, reject) {
 resolve('hello2');
})
(function (res) {
 (res); // hello2
});

Directly return failed asynchronous object through the () static method

var p = ('err')
(null, function (res) {
 (res); // err
});

Equivalent to, as follows:

var p = new Promise(function (resolve, reject) {
 reject('err2');
})
(null, function (res) {
 (res); // err
});

Test Promise application in object-oriented

'use strict';
class User{
 constructor(name, password) {
   = name;
   = password;
 }
 send() {
  let name = ;
  return new Promise(function (resolve, reject) {
   setTimeout(function () {
    if(name === 'leo') {
     resolve('send success');
    }else{
     reject('send error');
    }
   });
  });
 }
 validatePwd() {
  let pwd = ;
  return new Promise(function (resolve, reject) {
   setTimeout(function () {
    if(pwd === '123') {
     resolve('validatePwd success');
    }else{
     reject('validatePwd error');
    }
   });
  })
 }
}
let user1 = new User('Joh');
()
 .then(function (res) {
  (res);
 })
 .catch(function (err) {
  (err);
 });
let user2 = new User('leo');
()
 .then(function (res) {
  (res);
 })
 .catch(function (err) {
  (err);
 });
let user3 = new User('leo', '123');
()
 .then(function (res) {
  return ();
 })
 .then(function (res) {
  (res);
 })
 .catch(function(error) {
  (error);
 });
let user4 = new User('leo', '1234');
()
 .then(function (res) {
  return ();
 })
 .then(function (res) {
  (res);
 })
 .catch(function(error) {
  (error);
 });

For more information about JavaScript, please view the special topic of this site: "JavaScript object-oriented tutorial》、《Summary of JavaScript search algorithm skills》、《Summary of JavaScript Errors and Debugging Skills》、《Summary of JavaScript data structure and algorithm techniques》、《JavaScript traversal algorithm and skills summary"and"Summary of JavaScript mathematical operations usage

I hope this article will be helpful to everyone's JavaScript programming.