拒绝尝试/不等待的承诺

问题描述

demo1和demo2的唯一区别是demo2添加 await 。为什么demo1没有捕获到错误而demo2没有捕获到错误

// demo1
try {
    new Promise((resolve,reject) => {
        resolve()
    }).then(() => { throw new Error('haha') }) // Promise: {status: "rejected",value: Error: haha }
    console.log('irene test') // print 'irene test',execution is over.
} catch(err) { // didn't catch the error
    console.log('irene')
    console.log(err)
}

enter image description here

// demo2
try {
    await new Promise((resolve,reject) => {
        resolve()
    }).then(() => { throw new Error('haha') })
    console.log('irene test') // didn't print 'irene test'
} catch(err) { // catch the error
    console.log('irene') // print 'irene'
    console.log(err) // print err
}

enter image description here

解决方法

唯一的区别是此代码:

val df = spark.sparkContext.parallelize(Seq("2020-04-21 10:43:12.000Z","20-04-2019 10:34:12","11-30-2019 10:34:12","2020-05-21 21:32:43","20-04-2019","2020-04-21")).toDF("ts")

def strToDate(col: Column): Column = {
    val formats: Seq[String] = Seq("dd-MM-yyyy HH:mm:SS","yyyy-MM-dd HH:mm:SS","dd-MM-yyyy","yyyy-MM-dd")
    coalesce(formats.map(f => to_timestamp(col,f).cast(DateType)): _*)
  }

val formattedDF = df.withColumn("dt",strToDate(df.col("ts")))

formattedDF.show()
+--------------------+----------+
|                  ts|        dt|
+--------------------+----------+
|2020-04-21 10:43:...|2020-04-21|
| 20-04-2019 10:34:12|2019-04-20|
| 2020-05-21 21:32:43|2020-05-21|
|          20-04-2019|2019-04-20|
|          2020-04-21|2020-04-21|
+--------------------+----------+

等于这个:

library( data.table )
library( ggplot2 )
library( gridExtra )   #for merging two plots together

#sample data 
# !! ALTERED STOP_TIME IN ROW2 !!
DT <- fread("TASK_ID START_TIME   STOP_TIME     PERSON_ID TASK_GROUP
3983947 8/3/20T13:35 8/3/20T13:36 100       1
3983946 8/3/20T13:35 8/3/20T13:37 102       3
3983945 8/3/20T13:32 8/3/20T13:34 102       1
3983944 8/3/20T13:32 8/3/20T13:35 104       2
3983943 8/3/20T13:30 8/3/20T13:32 104       1
3983942 8/3/20T13:29 8/3/20T13:30 104       6
3983941 8/3/20T13:27 8/3/20T13:35 107       1
3983940 8/3/20T13:26 8/3/20T13:35 100       1
3983939 8/3/20T13:26 8/3/20T13:35 103       4
3983938 8/3/20T13:23 8/3/20T13:35 106       1
3983937 8/3/20T13:21 8/3/20T13:29 104       4
3983936 8/3/20T13:20 8/3/20T13:32 102       1
3983935 8/3/20T13:20 8/3/20T13:27 107       3
3983934 8/3/20T13:19 8/3/20T13:20 102       1
3983933 8/3/20T13:19 8/3/20T13:26 100       5")

#set timestamps to posixct
cols = grep( "TIME$",names(DT),value = TRUE )
DT[,(cols) := lapply( .SD,as.POSIXct,format = "%d/%m/%yT%H:%M"),.SDcols = cols ]

#create barchart
plot1 <- ggplot( data = DT ) + 
  geom_rect( aes( xmin = START_TIME,xmax = STOP_TIME,ymin = 0,ymax = 1,fill = as.factor(TASK_GROUP) ) ) +
  facet_wrap( ~PERSON_ID,ncol = 1,scales = "free_x" ) +
  coord_cartesian( xlim = c( min( DT$START_TIME,na.rm = TRUE ),max( DT$STOP_TIME,na.rm = TRUE ) ) ) +
  theme(axis.title.y = element_blank(),axis.text.y  = element_blank(),axis.ticks.y = element_blank()) + 
  guides(fill = FALSE)

#prepare data for piecharts
DT.pie <- DT[,duration := as.numeric( STOP_TIME - START_TIME ) ]
#calculate percentages
DT.pie[,percentage := duration / sum( duration ),by = .(PERSON_ID) ]

#create piechart
plot2 <- ggplot( data = DT.pie,aes( x = 1,y = percentage,fill = as.factor( TASK_GROUP ) ) ) +
  geom_bar( width = 1,stat = "identity" ) +
  facet_wrap( ~PERSON_ID,ncol = 1 ) +
  coord_polar(theta = "y",start=0) +
  theme(axis.title.x = element_blank(),axis.text.x  = element_blank(),axis.ticks.x = element_blank(),axis.title.y = element_blank(),axis.ticks.y = element_blank(),) + 
  labs( fill = "Task" )

#combine barchart and piechart
grid.arrange(plot1,plot2,ncol=2)

正如您在此处看到的,try { new Promise((resolve,reject) => { resolve() }).then(() => { throw new Error('haha') }) // Promise: {status: "rejected",value: Error: haha } console.log('irene test') // print 'irene test',execution is over. } catch(err) { // didn't catch the error console.log('irene') console.log(err) } 的范围与try catch的范围不同。

,

在demo1中,控制流在console.log('irene test')之后立即退出try catch块。因此,在Promise中引发错误之前,错误会不断发展。见下文。

try{
    new Promise((resolve,reject) => {
        resolve()
    }).then(() => { throw new Error('haha')})
    console.log('irene test')
} catch(err) { // catch the error
    console.log('irene') // print 'irene'
    console.log(err) // print err
}
console.log('already here')

result image 您会看到在打印“已经在这里”后引发错误。

如您所知,在demo2中,promise保留在try catch块中,直到引发错误为止。 (因为那是等待中的事情)

此外,如果即使出现错误也要打印“ irene测试”,最好使用.catch

new Promise((resolve,reject) => {
  resolve()
}).then(() => { throw new Error('haha')
}).catch(err => console.error(err))
console.log('irene test')

它成功地捕获了错误,并且还可以打印“ irene测试”。