Promise.allSettled polyfill

3,023 阅读1分钟

来自文章《Promise.allSettled的使用简介与功能实现》

Promise.allSettled = Promise.allSettled || function (arr) {
      var P = this;
      return new P(function(resolve,reject) {
        if(Object.prototype.toString.call(arr) !== '[object Array]') {
	  return reject(new TypeError(typeof arr + ' ' + arr +
          ' ' +' is not iterable(cannot read property Symbol(Symbol.iterator))'));
	}
	var args = Array.prototype.slice.call(arr);
	if (args.length === 0) return resolve([]);
	var arrCount = args.length;
 
	function resolvePromise(index, value) {
	  if(typeof value === 'object') {
	    var then = value.then;
	    if(typeof then === 'function'){
	      then.call(value,function(val) {
	        args[index] = { status: 'fulfilled', value: val};
	          if(--arrCount === 0) {
	             resolve(args);
                  }
	       }, function(e) {
                 args[index] = { status: 'rejected', reason: e };
	         if(--arrCount === 0) {
                   resolve(args);
                 }
               })
             }
           }
         }
 
          for(var i = 0; i < args.length; i++){
            resolvePromise(i, args[i]);
          }
       })
     }