javascript - How to delay excuting the code inside Promise? -
my code:
class mypromise extends promise { constructor(func) { super(func); } somepromiseextensionmethod() { // stuff... } } let test = async function() { let promise = new mypromise(function (resolve) { console.log('foo'); resolve(); }); console.log('start printing:'); await promise; }; test();
i'm leaning promise
, want create class derived promise
class.
my question: there way delay printing foo
until call await promise
?
update:
i want create class because want run methods while object promise
. (just like: mypromise.somepromiseextensionmethod()
).
update 2: real project:
let task = (function () { let __data = {}; __data.run = function (...args) { if (args.length) { let func = args[0]; return new task(func); } }; class task extends promise { constructor(action) { super(action); } static set run(value) { return __data.run; } static run() { return (...args) => __data.run.call(this, ...args); } } return task; }()); let test = async () => { let task = task.run(r => r(console.log('foo'))); console.log('start printing'); await task; }; test();
is there way delay printing
foo
until callawait promise
?
yes, known "lazy" promises. notice await
sugar calling then
method, can overwriting then
method , run executor callback:
class mypromise extends promise { constructor(func) { let run; super((resolve, reject) => { run = () => func(resolve, reject); }); this.run = run; } then(onfulfilled, onrejected) { const run = this.run; if (run) { this.run = null; run(); } return super.then(onfulfilled, onrejected); } } (async function test() { let promise = new mypromise(function (resolve) { console.log('foo'); resolve(); }); console.log('start printing:'); await promise; }());
please use learning exercise, wouldn't recommend use pattern in actual project.
Comments
Post a Comment