promise

promise大法好

平时大家写promise,或者说封装promise方法的时候是不是都要这样,各种 new Promise,举个栗子:

正常promise

var getJSON = function(url) {
  var promise = new Promise(function(resolve, reject){
    const randNum = Math.random() * num * 2;
    if (randNum > num) {
          resolve('win!');
      } else {
          reject('lost!');
      }
  });
  return promise;
};

getJSON(5).then(function(res) {
  console.log('result: ' + res);
}, function(error) {
  console.error('result', error);
});

封装promise

那么我们可以封装一个promise对象:

exports.getDefer = () => {
     const deferred = {};
     deferred.promise = new Promise((res, rej) => {
          deferred.resolve = res;
          deferred.reject = rej;
     })
}

然后用起来!

 const getJSON = (num) => {
   const deferred = getDefer();
   const randNum = Math.random() * num * 2;
   if (randNum > num) {
           deferred.resolve('win!');
       } else {
           deferred.reject('lost!');
       }
   return deferred.promise;
 };
 getJSON(5).then(function(res) {
   console.log('result: ' + res);
 }, function(error) {
   console.error('result', error);
 });

 // 还可以这样用。ES7
 (async()=>{
   try {
     const res = await getJSON(5);
     console.log('result: ' + res);
   } catch (error) {
     console.error('result', error);
   }
 })();

then加callback

同时支持callback回调和then函数:

 const getJSON = (num, callback) => {
   const deferred = getDefer();
   if (!callback) {
     return getJSON(num, (err, ret) => {
       if (err) {
         deferred.reject(err);
       } else {
         deferred.resolve(ret);
       }
       return deferred.promise;
     });
   }
   const randNum = Math.random() * num * 2;
   if (randNum < num) {
     return callback('lost!');
   }
   return callback('win!');
 };

 getJSON(5).then(function(res) {
   console.log('result: ' + res);
 }, function(error) {
   console.error('result', error);
 });

 getJSON(5, function (res) {
   console.log('result: ' + res);
 });