gpt4 book ai didi

javascript - Promise.resolve() 是如何工作的?具体来说,它究竟是如何打开 thenables 的?

转载 作者:行者123 更新时间:2023-12-01 16:04:09 25 4
gpt4 key购买 nike

根据 MDN:

...if the value is a thenable (i.e. has a "then" method), the returned promise will "follow" that thenable, adopting its eventual state;

这激起了我的兴趣,所以我想看看是否有可能用纯 Javascript 重新实现这个功能。我最终得到的是:

function resolve(p){
if (
p !== null &&
(
typeof p === "object" ||
typeof p === "function"
) &&
typeof p.then === "function"
) {
return p.then(
function resolved(value){
return new Promise( function (resolve, reject) {
resolve(value);
});
},
function rejected(error){
return new Promise( function (resolve, reject) {
reject(error);
});
}
);
}
else {
return new Promise( function (resolve, reject) {
resolve(p);
});
}
}

所以我用各种值对此进行了测试:

var a = new Promise (resolve => resolve("hello"));
var b = "hello";
var c = {
then: onFulfilled => onFulfilled("hello")
};
var d = {
then: onFulfilled => {
onFulfilled("hello")
}
}

Promise.resolve(a); //Promise {<resolved>: "hello"}
Promise.resolve(b); //Promise {<resolved>: "hello"}
Promise.resolve(c); //Promise {<resolved>: "hello"}
Promise.resolve(d); //Promise {<resolved>: "hello"}

resolve(a); //Promise {<resolved>: "hello"}
resolve(b); //Promise {<resolved>: "hello"}
resolve(c); //Promise {<resolved>: "hello"}
resolve(d); //undefined -- uh oh.

很明显,因为 dthen 方法没有返回任何东西,所以结果是未定义的……但是如果我正确地看这个,Promise.resolve () 正在以某种方式提取这个值?是不是自动把onFulfilled函数调用的返回值拉出来了?还是我完全看错了?

最佳答案

Promise.resolve 不依赖于 .then() 对 thenable 值调用的返回值。它看起来类似于:

function resolve(v) {
return new Promise((resolve, reject) => {
if (Object(v) === v && typeof v.then === "function") {
v.then(resolve, reject);
} else {
resolve(v); // fulfill (no recursive resolution)
}
});
}

这通常称为 Promise constructor antipattern , 但当我们不能信任 then 方法时,这是有保证的。我建议看看如何 Promises/A+指定处理 thenables。

关于javascript - Promise.resolve() 是如何工作的?具体来说,它究竟是如何打开 thenables 的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62621645/

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