function sleep(time) {
// body...
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, time * 1000)
})
}
function next() {
console.log("我被延时调用了");
}
sleep(3).then(() => {
next()
})
想要实现单独的then 链式操作 只需要 把要执行的函数实现用 Promise包含就可以
class People {
constructor(name) {
this.name = name;
this.sayHello();
this.queue = Promise.resolve();
}
sayHello() {
console.log(`hello, ${this.name}`);
}
sleep(time) {
this.queue = this.queue.then(() => {
return new Promise(res => {
setTimeout(() => {
res();
}, time * 1000)
})
})
return this;
}
eat(food) {
this.queue = this.queue.then(() => {
console.log(`${this.name} eat ${food}`);
})
return this;
}
}
// 1) 调用方式
new People('whr').sleep(3).eat('apple').sleep(5).eat('durian');
// 2) 打印结果
// 'hello, whr' - (等待3s) -- > 'whr eat apple' - (等待5s) -- > 'whr eat durian'
上面的例子是使用了类的方法/成员调用,每个方法都会返回一个promise this,而且这个this 的其他方法都在调用了this的 queue 队列成员,从而实现类的链式调用