努力让异步一点也不麻烦
很简单的例子:
var promise = new Promise(function(resolve, reject){
//执行成功时调用resolve, 当失败调用reject
setTimeout(function(){
resolve("ok!"); //代码正常执行!
}, 1000);
});
promise.then(function(msg){
console.log(successMessage);// ok
});
自己模拟一下上面的效果
// XXY version of promise
window.Xxythen = function(instantiation){
var then = []
// subscription
function on(param){
then.push(param)
}
// publish
function reject(){
console.error('[then end]')
}
function resolve(e){
then.forEach(function(re){
re(e)
})
}
instantiation(resolve,reject)
return {
then: param=>{
on(param)
}
}
}
// instantiation
var xxythen = new Xxythen((resolve,reject)=>{
window.setTimeout(function(){
resolve(0)
},2000)
})
xxythen.then((a)=>{
console.log(a)
})
xxythen.then((a)=>{
console.log(a)
})
OK,完美,promise的用处远远不止这些,先写这些,日后再更新。