gpt4 book ai didi

javascript - 实现最低限度的 Promise 函数来理解其他 Promise 框架

转载 作者:行者123 更新时间:2023-12-03 00:43:11 25 4
gpt4 key购买 nike

我一直在尝试理解 javscript 中 promise 调用背后的架构,我认为这是在幕后发生的事情

function Promise() {

this.stack = [];

this.then = function(fn) {
this.stack.push(fn);
return this;
}

this.resolve = function(data) {

if (this.stack.length) {
var cb = this.stack[0];

this.stack.shift();
cb.call(null, {
resolve: this.resolve.bind(this)
}, data);
}

}
}


// --- below is a working implementation --- //

var bar = function() {
var promise = new Promise();
setTimeout(function() {
console.log("1");
promise.resolve();
}, 2000);
return promise;
}

bar().then(function(p) {
setTimeout(function() {
console.log("2");
p.resolve();
}, 1000);
}).then(function(p) {
setTimeout(function() {
console.log("3");
p.resolve();
}, 500);
}).then(function(p) {
setTimeout(function() {
console.log("4");
p.resolve();
}, 300);
});

在我的库中,每次 resolve 调用之后,我都会调用堆栈中的下一个回调并将数组移动一个

但是在我链接的其他库中,每次解决第一个 promise 时,都会在整个数组中运行一个循环,同时不断调用回调堆栈。

D.js

function execCallbacks() {
/*jshint bitwise:false*/
if (status === 0) {
return;
}
var cbs = pendings,
i = 0,
l = cbs.length,
cbIndex = ~status ? 0 : 1,
cb;
pendings = [];
for (; i < l; i++) {
(cb = cbs[i][cbIndex]) && cb(value);
}
}

tiny Promise.js

_complete: function(which, arg) {
// switch over to sync then()
this.then = which === 'resolve' ?
function(resolve, reject) {
resolve && resolve(arg);
} :
function(resolve, reject) {
reject && reject(arg);
};
// disallow multiple calls to resolve or reject
this.resolve = this.reject =
function() {
throw new Error('Promise already completed.');
};
// complete all waiting (async) then()s
var aThen, i = 0;
while (aThen = this._thens[i++]) {
aThen[which] && aThen[which](arg);
}
delete this._thens;
}

tiny closure Promise.js

function complete(type, result) {
promise.then = type === 'reject' ?
function(resolve, reject) {
reject(result);
} :
function(resolve) {
resolve(result);
};

promise.resolve = promise.reject = function() {
throw new Error("Promise already completed");
};

var i = 0,
cb;
while (cb = callbacks[i++]) {
cb[type] && cb[type](result);
}

callbacks = null;
}

我想了解,为什么要在数组中运行一个循环来处理链接到解析的下一个函数!我的架构中缺少什么?

最佳答案

in my library, after every resolve call, i am calling the next callback in the stack and shifting the array by one

这是一个回调队列,而不是一个 promise 。 promise 只能解决一次。当创建 .then() Promise 链时,它只是创建多个 Promise 对象,每个对象代表一步后的异步结果。

您可能想看看the core features of promises .

关于javascript - 实现最低限度的 Promise 函数来理解其他 Promise 框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53353564/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com