Fork me on GitHub

李可

导航

async generator promise异步方案实际运用

es7 async方案


/******************async***********************/
var timeFn=function(time){
	return new Promise(function(resolve,reject){
		setTimeout(function(){
			console.log(2)
            resolve(3);
		},time)
	})	
}


var asyncFn=async function (){
	console.log(1)
	var parm=await timeFn(5000);
	console.log(parm)
	console.log(4)
}
asyncFn()

generator方案

/******************generator***********************/
var timeFn=function(time){
	return new Promise(function(resolve,reject){
		setTimeout(function(){
			console.log(2)
            resolve(3);
		},time)
	})	
}


var genFn=function * (){
	console.log(1)
	var parm=yield timeFn(5000);
	console.log(parm)
	console.log(4)
}
asyncFn()

promise方案

/******************promise***********************/
var timeFn=function(time){
	return new Promise(function(resolve,reject){
		setTimeout(function(){
			console.log(2)
            resolve(3);
		},time)
	})	
}



console.log(1)
timeFn(5000).then(function(parm){
	console.log(parm)
	console.log(4)
})

产品的需求

工作中的异步实用场景

ended 是音频播放完毕事件 btnText 是按钮文案

使用knockout库

        self.timer = ko.observable(3);
        self.focusChoice.subscribe((newVal)=>{
            if (newVal == '单词') {
                self.timer(3)
            } else {
                self.timer(5)
            }
        })
        self.btnText = ko.observable(`提交`)
        self.disabled = ko.observable(false);
        self.ended = async ()=> {
            console.log(1)
            self.btnText(`${self.timer()}秒后可以提交`)
            console.log(2)
            await self.promiseTime();
            console.log(3)
            self.btnText('提交')
            console.log(4)
        }
        
        self.promiseTime = ()=> {
            return new Promise((resolve)=> {
                setTimeout(() => {
                    self.disabled(true);
                    resolve();
                }, self.timer() * 1000)
            })
        }
           

gif

posted on 2017-06-29 19:50  李可在江湖  阅读(334)  评论(0编辑  收藏  举报