美文网首页
#JS#Promise速查

#JS#Promise速查

作者: a5c0a9d9ccb8 | 来源:发表于2016-11-16 14:18 被阅读19次
  1. 基础写法
var promise = new Promise(function ( resolve, reject ){
  //do sth
  resolve("success");
});
promise.then(function (value){
  console.log(value);//success
}, function(err){
  console.log(err);//reject执行
},)

如果只想对异常处理,可以采用<code>promise.then( undefined, onRejected )</code>or<code>promise.catch( onRejected )</code>

  1. return a Promise对象
function asyncFunction() {
  return new Promise(function ( resolve, reject ) {
    setTimeout( function () { 
      reject("error");
     } , 16);
  });
}
asyncFunction().then( undefined, function (err) {
  console.log(err);//error
} )
========================================================
function getUrl(URL){
  return new Promise ( function ( resolve, reject ){
    var req = new XMLHttpRequest();
    req.open("GET", URL, true);
    req.onload = function () {
      if ( req.status == 200 ){
        resolve( req.responseText );
      } else {
        reject( new Error( req.statusText ) );
      }
    };
    req.onerror = function () {
        reject( new Error( req.statusText ) );
    };
    req.send();
  } )
}
//running
var URL = "http://httpbin.org/get";
getUrl(URL).then( function onFulfilled ( value ) {
  console.log(value);
}).catch( function onRejected ( error ){
  console.error(error);
});
  1. Promise的处理流程
    三状态
  • Settled不变的
    • "has-resolution"resolve成功
    • "has-rejection"reject失败
  • "unresolved"pending等待
  1. promise chain
function taskA() {
    console.log("Task A");
}
function taskB() {
    console.log("Task B");
}
function onRejected(error) {
    console.log("Catch Error: A or B", error);
}
function finalTask() {
    console.log("Final Task");
}
var promise = Promise.resolve();
promise
    .then(taskA)
    .then(taskB)
    .catch(onRejected)
    .then(finalTask);
======log======
Task A
Task B
Final Task
  1. Promise和数组——Promise.all
// `delay`毫秒后执行resolve
function timerPromisefy(delay) {
    return new Promise(function (resolve) {
        setTimeout(function () {
            resolve(delay);
        }, delay);
    });
}
var startDate = Date.now();
// 所有promise变为resolve后程序退出
Promise.all([
    timerPromisefy(1),
    timerPromisefy(32),
    timerPromisefy(64),
    timerPromisefy(128)
]).then(function (values) {
    console.log(Date.now() - startDate + 'ms');
    // 約128ms
    console.log(values);    // [1,32,64,128]
});
//======log=====等待所有resolve完成后输出
131ms
1,32,64,128
  1. Promise和数组——Promise.race
    Promise.all在接收到的所有的对象promise都变为 FulFilled 或者 Rejected 状态之后才会继续进行后面的处理,与之相对的是 Promise.race只要有一个promise对象进入FulFilled 或者 Rejected 状态的话,就会继续进行后面的处理。

参考

JavaScript Promise迷你书

AngularJS+LeanCloud+promise.all+echarts

var OPTIONS =["其他问题","车辆问题"];
var conditions = [];
$scope.sum = 0;
$scope.resData = [];

for(index in OPTIONS){
    var condition = {
        index:index,
        opts:OPTIONS[index]
    }
    conditions.push(condition);
}
var promises = [];
angular.forEach(conditions , function (condition) {
    var deferred = $q.defer();
    var query = new AV.Query("Feedback");
    query.equalTo("reason", condition.opts)
    query.count().then(function (count) {
        $scope.sum += count;
        $scope.resData.push({
            index:condition.index,
            datax:OPTIONS[condition.index],
            datay:count
        })
        deferred.resolve();
    }, function (error) {
        deferred.reject();
    });
    promises.push(deferred.promise);
})
$q.all(promises).then(function () {
    $scope.resData.sort(function (a,b) {return a.index-b.index;})
    $scope.makeChart($scope.resData,"pie");
})

相关文章

网友评论

      本文标题:#JS#Promise速查

      本文链接:https://www.haomeiwen.com/subject/ufnkpttx.html