2017-04-10 96 views
0

這是用於香草JavaScript的。一旦另一個函數完全結束,我不想執行一個函數。現在,我確實有一些作品,但我想這是可以做到更好:(JavaScript)從其他函數執行回調函數

setTimeout(function() { 
    // does things with the variables a, b(array) and c 
}, 500); 
function happySunshine(some inparameters){ 
    // calculates and sets variables a, b(array) and c 
} 

的happySunshine功能必須打好不幸後的順序我的setTimeout函數,這不能改變。

現在這個工作,因爲happySunshine函數將執行並完成它的任務在setTimeout被設置爲等待執行之前的半秒。

所以......我不知道。有沒有辦法讓一個函數按順序排在第一位,等到另一個函數(在訂單後面)完成之後才能執行?

重要的是要注意的是,這些功能不能在相同的範圍內。

+0

爲什麼'setTimeout()'調用是必需的? – guest271314

+0

爲什麼不在之前聲明函數並從happySunshine()中調用它?如果需要,您甚至可以傳遞參數。 – mligor

+0

setTimeout()是我現在解決問題的方式,我實際上不需要它。 –

回答

1

可以從happySunshine()返回Promise.resolve()Promise構造與設置爲一個具有對象特性值和值abc

function happySunshine(/* some inparameters */){ 
    // calculates and sets variables a, b(array) and c 
    // return new Promise(function(resolve, reject) { 
     // do stuff 
     // resolve({a:a, b:[], c:c}); 
    // }); 
    return Promise.resolve({a:a, b:[], c:c}); 
} 

happySunshine(/* some inparameters */) 
.then(function({a, b, c}) { 
    // does things with the variables a, b(array) and c 
}) 
+0

這看起來很有趣,但我並不是很瞭解它。你能解釋它的作用嗎?謝謝你幫助我! –

+0

請參閱[你錯過了諾言](https://gist.github.com/domenic/3889970) – guest271314

+0

謝謝guest271314 –

0

你有沒有嘗試過這樣的事情

function initialFunction(){ 
//Do you magic here 
happySunShine(params); 
} 

你happySunShine()方法應該是全球可用,否則這將無法工作。

+0

謝謝Spharah,但我不thik這將工作,因爲「/ /你在這裏魔術」是依賴於happySunShine(params)將執行之前。 –