Promise - Part 7 of 函数式编程
-
Promise (承诺) 函数用于实现callback的功能,即在一个函数结束后调用另外一个函数。
比如下面这个例子:function do_thing1(){ setTimeout( function(){ console.log( 'do thing1' ); }, 1000 ); } function do_thing2(){ console.log( 'do thing2' ); } do_thing1(); do_thing2();
这里我们先调用do_thing1因为我们希望
do_thing2
在do_thing1
结束后再执行,但是do_thing2没有等!我们可以用传统的callback来解决这个问题如下:
function do_thing1(callback){ setTimeout( function(){ console.log( 'do thing1' ); callback && callback() }, 1000 ); } function do_thing2(){ console.log( 'do thing2' ); } do_thing1(do_thing2);
我把do_thing2当做一个变量传给do_thing1,等do_thing1结束后来调用do_thing2。
接下来,我们用Promise来解决这个问题:
const do_thing1b = new Promise((resolve, reject) => setTimeout(() => { console.log("do_thing1b"); resolve("done"); }, 1000) ); const do_thing2b = () => { console.log("do thing2b"); }; do_thing1b.then(() => do_thing2b());
因为do_thing1b现在是个Promise,所以我们可以用then来串接其他函数,即do_thing2,这样就确保do_thing2b一定在do_thing1b结束后才被调用。这就"承诺"!