ES6 Promises
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ES6 Promises相关的知识,希望对你有一定的参考价值。
Promises通过一种简单干净的方法实现javascript的异步编程,它是ES6的新功能。先看下面几个例子(可以使用node测试):
SyncCallback(同步回调):
function notifyAll(a, b) { console.log("starting notification process"); a(); b(); } function notify1() { console.log("Hey, one."); } function notify2() { console.log("Hey, two."); } notifyAll(notify1, notify2);
AsyncCallback(异步回调,基于setTimeout):
function notifyAll(a, b) { setTimeout(function(){ console.log("starting notification process"); a(); b(); }, 2000); } function notify1() { console.log("Hey, one."); } function notify2() { console.log("Hey, two."); } notifyAll(notify1, notify2);
再看一个基于setTimeout极端的异步回调:
setTimeout(function() { console.log("one"); setTimeout(function() { console.log("two"); setTimeout(function() { console.log("three"); }, 1000); }, 1000); }, 1000);
好了,ES6 Promises来了:
function getSum(n1, n2) { varIsNegative = function() { return n1 < 0 || n2 < 0; } var promise = new Promise(function(resolve, reject) { if (varIsNegative()) { reject(Error("Negatives not supported.")); } resolve(n1 + n2); }); return promise; } getSum(5, 7).then( function(result) { console.log(result); }, function(error) { console.log(error); } );
现在是ES6 Promises的连续事件(Continuation Events):
function getSum(n1, n2) { var checkNums = function() { return n1 < 0 || n2 < 0; } var promise = new Promise(function(resolve, reject) { if (checkNums()) { reject(Error("Invalid number input.")); } resolve(n1 + n2); }); return promise; } getSum(2, 3) .then(function(result) { console.log(result); return getSum(10, 20); }, function(error) { console.log(error); }) .then(function(result) { console.log(result); }, function(error) { console.log(error); });
以上是关于ES6 Promises的主要内容,如果未能解决你的问题,请参考以下文章
ES6 Promises - 类似 async.each 的东西?
[Node.js] Testing ES6 Promises in Node.js using Mocha and Chai