标签:else 接口 col UNC stat open 因此 sync user
new Promise(function(resolve,reject){ });
var aPromise = new Promise(function (resolve) { resolve(100); }); var thenPromise = aPromise.then(function (value) { console.log(value); }); var catchPromise = thenPromise.catch(function (error) { console.error(error); }); console.log(aPromise !== thenPromise); // => true console.log(thenPromise !== catchPromise);// => true
getUserByName(‘xxx‘).then(function(user){ if(imMemoryCache[user.id]){ return inMemoryCache[user.id]; } return getUserAccountById(user.id); }).then(function(userAccount){ });
new Promise(function(resolve,reject){ resolve(syncValue); }).then(/*...*/) //可以写成 Promise.resolve(syncValue).then(/*...*/) //一个错误也可以写成 Promise.reject(new Error(‘...‘))
Promise.resolve(‘foo‘).then(Promise.resolve(‘bar‘)).then(function(result){ console.log(result); }); //会被解释为: Promise.resolve(‘foo‘).then(null).then(function(result){ console.log(result); });
// 写法一 f1().then(function () { return f2(); }); // 写法二 f1().then(function () { f2(); }); // 写法三 f1().then(f2()); // 写法四 f1().then(f2);
promise1.then(function(){ return promise2; }).then(function(){ return promise3; }).then(function(){ return promise4; }).catch(function(err){ console.log(err); });
function executeSequentially(promiseFactories){ var res = Promsie.resolve(); promiseFactories.forEach(function(promiseFactory){ res = res.then(promiseFactory); }); return res; } //工厂函数只是简单的创建一个promise function promiseFactory(){ return createAPromise(); }
//原生版本 function Http(){ } Http.prototype = { get:function(opts){ return this.ajax(opts); }, post:function(){ return this.ajax(opts); }, ajax:function(opts){ return Promise(function(resolve,reject){ var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject(‘...‘); var {url,method,data,async,success,fail} = options; var sendBody = null; var qs = Object.keys(data).reduce(function(cur,pre,index){ return pre + ‘&‘ + encodeURIComponent(cur) + ‘=‘ + encodeURIComponent(data[cur]); },‘‘).slice(1); if(medthod == ‘get‘){ url += ‘?‘ + qs; } else if(medhot == ‘post‘){ xhr.setRequestHeader(‘Content-type‘, ‘application/x-www-form-urlencoded‘); sendBody = qs || null; } xhr.onreadystatechange = function(){ if(xhr.readystate == 4){ if(xhr.status >= 200 && xhr.status < 300 || xhr.status == 304){ resolve(xhr,xhr.responseText); } } else{ reject(xhr,xhr.responseText); } } xhr.open(method,url,async); xhr.send(sendBody); }); } } //jquery版本 function Http(){ } Http.prototype = { get:function(opts){ return this.ajax(opts); }, post:function(opts){ return this.ajax(opts); }, ajax:function(){ return $.ajax(opts); } }
标签:else 接口 col UNC stat open 因此 sync user
原文地址:https://www.cnblogs.com/mengff/p/9646392.html