实施异步/等待角度7

时间:2020-10-02 16:28:37

标签: angular typescript

有人可以帮我为这个角度/打字稿方法实现异步/等待吗

onCustomerSelected(cId) {
    let cust = this.custlist.find((c) => c.custId == cId);

    this.service.setCustomer(cust); //need to await this method (note, this doesnt return promise)

    ... do some processing ...
    (note, i need to wait for the service to set customer first, before i can begin further processing)   
}

2 个答案:

答案 0 :(得分:1)

假设this.service.setCustomer返回一个Promise,则只需将功能onCustomerSelected标记为async,然后将await this.serice.setCustomer

async onCustomerSelected(cId) {
    let cust = this.custlist.find((c) => c.custId == cId);

    await this.service.setCustomer(cust); //need to await this method (note, this doesnt return promise)

}

如果this.service.setCustomerObservable,那么您需要做await this.service.setCustomer(...).toPromise();

答案 1 :(得分:1)

您需要将服务呼叫包装在Promise中,并使用await。

library(caret) library(mlbench) library(randomForest) res <- matrix(0, nrow = 10, ncol = 6) colnames(res) <- c("mtry","Threshhold","Accuracy", "PositivePred", "NegativePred", "F-value") out <- matrix(0, nrow = 17, ncol = 6) colnames(out) <- c("mtry","Threshhold","Avg.Accuracy", "Avg.PosPred", "Avg.NegPred", "Avg.F_Value") rep <- matrix(0, nrow = 10, ncol = 6) colnames(out) <- c("mtry","Threshhold","Avg_Accuracy", "Avg_PosPred", "Avg_NegPred", "Avg_F_Value") data(Sonar) N=Sonar ### creating 10 folds folds <- cut(seq(1,nrow(N)),breaks=10,labels=FALSE) for (mtry in 5:14) { K=mtry-4 for(thresh in seq(1,9,0.5)) { J = 2*thresh-1 dataset<-N[sample(nrow(N)),] #### mix up the dataset N for(I in 1:10){ #Segement your data by fold using the which() function testIndexes <- which(folds==I,arr.ind=TRUE) N_test <- dataset[testIndexes, ] ### select each fold for test N_train <- dataset[-testIndexes, ] ### select rest for training rf = randomForest(Class~., data = N_train, mtry=mtry, ntree=500) pred = predict(rf, N_test, type="prob") label = as.factor(ifelse(pred[,2]>=thresh,"M","R")) confusion = confusionMatrix(N_test$Class, label) res[I,1]=mtry res[I,2]=thresh res[I,3]=confusion$overall[1] res[I,4]=confusion$byClass[3] res[I,5]=confusion$byClass[4] res[I,6]=confusion$byClass[7] } print(res) out[J,1] = mtry out[J,2] = thresh out[J,3] = mean(res[,2]) out[J,4] = mean(res[,3]) out[J,5] = mean(res[,4]) out[J,6] = mean(res[,5]) } print(out) rep[K,1] = mtry rep[K,2] = thresh rep[K,3] = mean(out[,2]) rep[K,4] = mean(out[,3]) rep[K,5] = mean(out[,4]) rep[K,6] = mean(out[,5]) } print(rep)