Answer the question
In order to leave comments, you need to log in
How does Promise.resolve work in Javascript?
Good afternoon everyone. Recently I came across one piece of code that I do not quite understand. I have a good understanding of what promises are and how working with them is made easier by async/await. For example, in the following code, no questions arise:
const func = async () => {
return 100;
};
func()
.then( res => {
console.log(res);
return 200;
})
.then( res => {
console.log(res);
});
/**
* Expected output:
* 100
* 200
*/
func
:const func = async () => {
/** ??? */
};
func()
.then( res => {
console.log(res);
return 200;
})
.then( res => {
console.log(res);
})
.resolve(100);
/**
* Expected output:
* 100
* 200
*/
Answer the question
In order to leave comments, you need to log in
const deferred = () => {
Promise.prototype.resolve = () => {}; // чтобы не было ошибок )
return Promise.resolve("web");
}
// проверка
deferred()
.then(function(res) {
console.log(200, res);
return "lab";
})
.then(function(res) {
console.log(100, res);
})
.resolve("web");
// реализация
function deferred() {
function Box() {
this.queue = [];
}
Box.prototype.then = function(func) {
this.queue.push(func);
return this;
}
Box.prototype.resolve = function(first_arg) {
let arg = first_arg;
while (this.queue.length)
arg = this.queue.shift().call(this, arg);
}
return new Box;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question