Me pidieron que creara un objeto llamado foo que pudiera encadenar el log funciones y wait .
Por ejemplo:
foo.log('breakfast').wait(3000).log('lunch').wait(3000).log('dinner'); En este escenario, primero imprime el breakfast , espera 3 segundos, imprime el lunch y luego, después de 3 segundos, imprime la dinner .
Intenté algo como esto, pero no funciona. ¿Qué me perdí?
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');Más corto, dentro de Promise (no recomendado).
Promise.prototype.log = function(txt) { return this.then(() => console.log(txt)) } Promise.prototype.wait = function(ms) { return this.then(() => new Promise(res => setTimeout(res, ms))) } var foo = Promise.resolve() foo.log('breakfast').wait(3000).log('lunch').wait(3000).log('dinner')Siempre es mejor usar promesas. Una implementación de esta funcionalidad podría ser;
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");