用纯JavaScript等待回调

时间:2018-10-27 21:16:40

标签: javascript function asynchronous callback

我正在寻找一种在我的程序中进一步执行之前等待函数调用的方法。这是我之前研究过的东西,下面有一些小技巧,我可以先向您介绍:

data2$gender =as.factor(data2$gender)

data2$intyorn =as.factor(data2$intyorn)

data2$EducAge20Recoded =as.factor(data2$EducAge20Recoded)

mylogit <- glm(EducAge20Recoded ~ gender + intyorn+ prs_ea_all + gxeaALL, data = data2, family = "binomial")

data3 <- with(data2, data.frame(prs_ea_all = mean(prs_ea_all), **intyorn**, gxeaALL = mean(gxeaALL), gender = factor(0:1)))

data3$genderP <- predict(mylogit, newdata = data3, type = "response")

newdata2 <- with(data2, data.frame(prs_ea_all = rep(seq(from = -4, to = 4, length.out = 100), ##2), gxeaALL = mean(gxeaALL), intyorn, gender = factor(rep(0:1, each = 100))))

但是,我正在寻找一种等待回调的特定方法。基本上,我希望触发// You can wrap the rest of your code in the callback /* executing code */ asyncFunction((err, callback)=>{ if(err)console.log(err) else{ /* The rest of your program */ } }) // You can do function chaining (use this to parallel asyncs) var arr = newArray(2).fill(false) asyncParallel() function asyncParallel(){ asyncFunction1((err,callback)=>{ if(err)console.log(err) else{ arr[arr.indexOf(false)] = true allDone() } } asyncFunction2((err, callback)=>{ if(err)console.log(err) else{ arr[arr.indexOf(false)] = true allDone() } } } function allDone(){ if(!arr.includes(false)){ theRest() } } function theRest(){ /* the rest of your code */ } // You can wrap all of your code in a generator function function* gen(){ /* your code */ yield something /* the rest of your code */ } var g = gen() g.next() asyncFunction((err, callback)=>{ if(err)console.log(err) else{ g.next() } } //You could also download a fancy pants module which I have no time for ,然后我的程序只执行一步,然后碰到了一个塞子,在回调中我想释放该塞子。它应该看起来像这样:

axios.get

您可能会想放置一个while循环,但这将阻止任何其他代码的执行:

axios.get('myUrl').then(res=>{trigger()})
/* function to wait for trigger */
/* the rest of my code */

此外,设置超时在这种情况下将不起作用,因为它本身是一个异步函数,并且不会停止执行其他代码(除非将其包装在回调函数中调用的函数中):

var x = false
axios.get('myUrl').then(res=>{x = true})
while(x === false){
    // this will stop any other code from executing.
    // x will never be set to true.
}

有没有办法在我的回调中放置一个触发器,并有一个特殊的非代码阻止功能在推进任何其他代码之前先等待该触发器,而不必将我的所有代码包装在另一个函数中?我热切期待您的回答,希望这篇文章对人们有所帮助!

0 个答案:

没有答案