首页
题库
面试
求职
学习
竞赛
More+
所有博客
搜索面经/职位/试题/公司
搜索
我要招人
去企业版
登录 / 注册
首页
>
试题广场
>
promise实现
[问答题]
promise实现
查看答案及解析
添加笔记
求解答(0)
邀请回答
收藏(45)
分享
纠错
3个回答
添加回答
1
埋头苦干364天
const
PENDING
=
'PENDING'
const
FULFILLED
=
'FULFILLED'
const
REJECT
=
'REJECT'
class
Promise
{
constructor
(
exector
) {
this
.
state
=
'PENDING'
this
.
successData
=
undefined
this
.
errorData
=
undefined
this
.
resolveList
= []
this
.
rejectList
= []
const
resolve
= (
value
)
=>
{
if
(
this
.
state
==
'PENDING'
){
this
.
state
=
'FULFILLED'
this
.
successData
=
value
this
.
resolveList
.
forEach
(
fn
=>
fn
())
}
}
const
reject
= (
value
)
=>
{
if
(
this
.
state
==
'PENDING'
){
this
.
state
=
'REJECT'
this
.
errorData
=
value
this
.
rejectList
.
forEach
(
fn
=>
fn
())
}
}
try
{
exector
(
resolve
,
reject
)
}
catch
(
error
) {
reject
(
error
)
}
}
then
(
resolveFn
,
rejectFn
){
if
(
this
.
state
==
'FULFILLED'
) {
resolveFn
(
this
.
successData
)
}
if
(
this
.
state
==
'REJECT'
) {
rejectFn
(
this
.
errorData
)
}
if
(
this
.
state
==
'PENDING'
) {
this
.
resolveList
.
push
(()
=>
{
resolveFn
(
this
.
successData
)})
this
.
rejectList
.
push
(()
=>
{
rejectFn
(
this
.
errorData
)})
}
}
}
发表于 2022-03-21 21:45:06
回复(0)
0
许愿offerba
<
script
type
=
"text/javascript"
>
function
myPromise
(
constructor
){
let
self
=
this
;
self
.
status
=
"pending"
//定义状态改变时的初始状态
self
.
value
=
undefined
;
//定义状态为resolve时的值
self
.
reason
=
undefined
;
//定义状态为rejected的值
function
resolve
(
value
) {
if
(
self
.
status
===
"pending"
){
self
.
value
=
value
;
self
.
status
=
"resolved"
}
}
function
reject
(
reason
){
if
(
self
.
status
===
"pending"
){
self
.
reason
=
reason
;
self
.
status
=
"rejected"
}
}
//捕获构造异常
try
{
constructor
(
resolve
,
reject
);
}
catch
(
e
) {
reject
(
e
)
}
}
//同时需要在myPromise的原型上定义链式调用的then方法
myPromise
.
prototype
.
then
= (
onResolved
,
onRejected
)
=>
{
let
self
=
this
;
switch
(
self
.
status
){
case
"resolved"
:{
onResolved
(
self
.
value
);
break
;
}
case
"rejected"
:{
onRejected
(
self
.
reason
);
break
}
default
;
}
}
</
script
>
发表于 2022-03-20 16:27:21
回复(0)
0
牛客789741155号
const
PENDING
=
'pengding'
const
FULFILLED
=
'fulfilled'
const
REJECTED
=
'rejected'
class
MyPromise
{
constructor
(
executor
){
executor
(
this
.
resolve
,
this
.
reject
)
}
status
=
PENDING
value
=
null
resaon
=
null
resolve
=(
value
)
=>
{
if
(
this
.
status
==
PENDING
){
this
.
status
=
FULFILLED
this
.
value
=
value
}
}
reject
=(
resaon
)
=>
{
if
(
this
.
status
==
PENDING
){
this
.
status
=
REJECTED
this
.
resaon
=
resaon
}
}
then
(
onFulfilled
,
onRejected
){
if
(
this
.
status
==
FULFILLED
){
onFulfilled
(
this
.
value
)
}
else
if
(
this
.
status
==
REJECTED
){
onRejected
(
this
.
reason
)
}
}
}
发表于 2022-03-03 09:45:52
回复(0)
这道题你会答吗?花几分钟告诉大家答案吧!
提交观点
问题信息
上传者:
小小
难度:
3条回答
45收藏
446浏览
热门推荐
相关试题
如图 1 表示使用快表(页表)的虚...
编程基础
评论
(1)
对于我们来说,谁是好的顾客?
销售常识
评论
(1)
小红书用户在不同使用场景下,对内容...
需求分析
评论
(1)
MySQL中执行 SELECT I...
SQL
评论
(1)
订单表order_table全部记...
查找
数据库
数据分析
SQL
评论
(2)
扫描二维码,关注牛客网
意见反馈
下载牛客APP,随时随地刷题