一个好的程序员web前端教程分享如何使用promises解决回调和异步。首先,让我们看看以下问题的输出是什么?setTimeout(function(){console.log(1);},1000)console.log(2);我们得到的结果是:先输出2,再输出1;是什么原因?大家应该都知道定时器是异步的;所以先输出2;那么我们的需求来了,如何先输出1,再输出2呢?functionfoo(callback){setTimeout(function(){console.log(1);callback();},1000)}foo(function(){console.log(2);})现在让我们看看打印结果吧,果然先输出1,再输出2;这是通过回调函数解决的;现在你的需求变了,我们每1秒输出一次;functionfoo(callback){setTimeout(function(){console.log('1秒后输出');callback()},1000)}foo(function(){console.log('第一次输出');foo(function(){console.log('Secondoutput');foo(function(){console.log('Secondoutput');})})})这是否解决了我们的问题?是的,但是如果我们多来几次,大家会不会发现回调太多了?这就是大家所说的毁灭地狱;所以ES6为我们提供了一个摧毁地狱的解决方案:promise;promise是一种异步处理值的方法,promise是一个解决层层嵌套问题的对象promise对象的状态:进行中:pendingsuccess:resovledfailure:rejectedpromise对象方法:then()成功后执行;如果有两个参数:第一个参数成功后执行,第二个参数失败后执行;catch()失败后执行;Promiseall([]).then()在所有promise成功后执行graphthen的第一个方法;承诺.race[(p1,p2,p3,---)]只要有一个先改变状态,promise就会执行相应的状态varpromise=newPromise(function(resolved,rejected){resolved('ok');rejected('no');//如果success和failure同时写入,执行先写入的;(特征状态一旦改变,不可逆)});promise.then(function(msg){console.log('ok:'+msg);},function(msg){console.log('no:'+msg);});打印结果为:ok:ok现在我们做一个练习:使用promise加载一张图片;如果图片加载成功则加载到正文中,如果加载失败则提示失败;varpromise=newPromise(function(resolved,rejected){varimg=document.createElement('img');img.src='./img/1.png';img.onload=function(){resolved(img)//如果加载成功则返回resolved()}img.onerror=function(){rejected('failed')//如果加载成功则返回rejected()}})promise.then(function(msg){document.body.appendChild(msg)},function(msg){alert(msg)})怎么样?你知道承诺吗?那么如何使用promise解决异步问题呢?我们仍然每1秒输出一次;varpromise=newPromise(function(resolved,rejected){setTimeout(function(){console.log('everysecond');resolved()},1000)});returnpromise;}fn().then(function(){console.log('第一个输出');returnfn()}).then(function(){console.log('第二个输出');returnfn()}).then(function(){console.log('第三输出');})Promise是如何解决ajax回调的问题的?我们继续往下看。functionajaxPromise(url){varpromise=newPromise(function(resolved,rejected){varxhr=newXMLHttpRequest();xhr.open('get',url);xhr.send();xhr.onreadystatechange=function(){if(xhr.readyState===4&&xhr.status===200){resolved(xhr.responseText);//告诉promise成功}}setTimeout(function(){//5秒后,requestislessthanrejected('error')//tellpromisefailed},5000)})returnpromise;}document.onclick=function(){varpro=ajaxPromise('data.json');临。then(function(msg){alert(msg)//如果路径正确,我们获取数据},function(msg){alert(msg)//如果路径错误,我们弹出错误})}
