-
-
Notifications
You must be signed in to change notification settings - Fork 237
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
6. Promise.resolve #6
Comments
Promise.resolve = function (data) {
if (data instanceof Promise) {
return data;
}
return new Promise((resolve) => {
resolve(data);
});
};
|
@faga295 不重复, 不过确实没补充完全. 这里isPromise应该是要去判断是否thenable. 贴一段V8的源码 if (!IsJSPromiseMap(resolutionMap)) {
dcheck(IsJSReceiverMap(resolutionMap));
dcheck(!IsPromiseThenProtectorCellInvalid());
// 删掉了部分代码....
return FulfillPromise(promise, resolution);
} 可见v8在实现resolve时, 把promise和thenable的对象都滤去了, IsJSPromiseMap和IsPromiseThenProtectorCellInvalid这两个函数就是保证最终的value中没有then方法. 事实上你可以试一下: Promise.resolve({ then: (resolve) => resolve('xx') })
.then(res => console.log(res)) 这里打印出来的并不是一个带有then属性的对象, 而是'xx' |
|
function myResolve(value) {
// 如果 value 已经是 Promise 对象,则直接返回该 Promise 对象
if (value instanceof Promise) {
return value;
}
// 如果 value 是 thenable 对象,则包装成 Promise 对象并返回
if (value && typeof value.then === 'function') {
return new Promise(function(resolve, reject) {
value.then(resolve, reject);
});
}
// 将传入的值作为 Promise 的成功值,并返回 Promise 对象
return new Promise(function(resolve) {
resolve(value);
});
} |
Promise.resolve = function (data) { |
Promise.resolve = function (data) {
if (data instanceof Promise) {
return data;
}
return new Promise((resolve) => {
resolve(data);
});
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The text was updated successfully, but these errors were encountered: