A
A
artekha2017-01-23 21:45:15
JavaScript
artekha, 2017-01-23 21:45:15

How to write a promise yourself?

Hello, the task is to write your Promise. You just need to make it possible to chain requests as in promises, you don’t need to catch errors (catch). If you provide just materials for parting words on how promises work from the inside, or immediately how to implement them - thank you very much.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
Y
Yustas Alexu, 2017-01-23
@Yuxus

I think this should be enough https://www.promisejs.org/implementing/
However, after reading, even if you write a promise, it will no longer be your own version.

A
Alexander Aksentiev, 2017-01-23
@Sanasol

What does it mean to write yourself?
Native "function".
caniuse.com/#feat=promises
https://developer.mozilla.org/en/docs/Web/JavaScri...
ps
And there are enough implementations, you can see any.
What is the meaning of such a bike is just not clear.

R
Roman_Bednyakov, 2019-04-05
@Roman_Bednyakov

const deferred = function() {
this.allFunc = [];
this.lastResult;
}
deferred.prototype.then = function (newFunc) {
this.allFunc.push(newFunc);
}
deferred.prototype.resolve = function (arg) {
this.lastResult = arg;
for(let i = 0; i < this.allFunc.length; i++) {
const item = this.allFunc[i];
const res = item(this.lastResult);
if (res instanceof deferred) {
const lastFuncs = this.allFunc.slice(i+1);
res.allFunc = lastFuncs;
break;
} else {
this.lastResult = res;
}
}
}
const d = new deferred();
d.then(function(res){
console.log('1', res);
var d1 = new deferred();
setTimeout(function(){ d1.resolve("a"); }, 3000);
return d1 ;
});
d.then(function(res){ console.log("2 ", res); return "b"; });
d.then(function(res){ console.log("3 ", res); return "c"; });
d.resolve("hello");

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question