我被要求创建一个名为 foo
的对象可以链接函数log
和 wait
.
例如:
foo.log('breakfast').wait(3000).log('lunch').wait(3000).log('dinner');
在这种情况下,它会打印 breakfast
首先,等待 3 秒,打印 lunch
,然后在 3 秒后打印 dinner
.我尝试过这样的事情,但它不起作用。我错过了什么?
var foo = {
log: function(text){
console.log(text);
return foo;
},
wait: function(time) {
setTimeout(function() {
return foo;
}, time);
}
}
foo.log('breakfast').wait(3000).log('lunch').wait(3000).log('dinner');
最佳答案
使用 Promise 总是更好。此功能的实现可能是;
class Foo {
constructor(){
this.promise = Promise.resolve();
}
log(txt){
this.promise = this.promise.then(_ => console.log(txt))
return this;
}
wait(ms){
this.promise = this.promise.then(_ => new Promise(v => setTimeout(v,ms)));
return this;
}
}
var foo = new Foo();
foo.log("happy").wait(1000).log("new").wait(1000).log("year");
关于javascript - 如何使用 JavaScript 异步链接函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70541130/