[英]How to execute orderly too many function? Javascript
例:
function first()
{
alert('FIRST');
}
function second()
{
alert('SECOND');
}
function third()
{
alert('THIRD');
}
我要在第一個函數完成后按順序執行所有這些函數。
我使用的是setTimeout
但這也會根據每個函數的處理方式而產生錯誤。
例如,如果我在第二個和第三個函數中設置了setTimeout
,但是如果第一個函數包含某種無法立即執行的代碼怎么辦?
請幫我。
最簡單的方法是這樣。
function first()
{
alert('FIRST');
this.second(); // Call second function when first one is done...
}
function second()
{
alert('SECOND');
this.third(); // Call third when second function is done...
}
function third()
{
alert('THIRD');
}
first(); // This will execute first...
除了這種方式,您還可以通過多種方式來順序調用函數。
您可以使用,
1)異步/等待,
2)回調,
3)承諾(bluebird,promise)
我想我明白你要干什么。 正如其他人所發表的那樣,由於您當前的功能是同步的,因此可以一個接一個地調用它們。
first()
second()
third()
但是,您確實提到過“如果延遲了該怎么辦”。 因此,我們如何確保在完成一項操作時可以調用第二項,然后調用第三項,依此類推...
您必須了解諾言。 這些有點像合同,將來的某個時候,您會得到成功或失敗的通知。
就像程序/操作說:“我會盡快回答您的問題,但首先讓我嘗試獲得您想要的...”。 我想每個人對如何“理解概念”都有不同的解釋。 我只想說些類似“我有一個問題...。做您的研究,讓我知道他們是否是答案”之類的東西。然后您的應用程序返回“成功:這是您的答案”或“拒絕:抱歉,無法回答”。
因此,給出您的代碼。 我們需要采用這些功能中的每一個,並通過一個承諾包裝將它們的“問題”發送出去,以便我們可以將“問題”包裝在我正在談論的這個承諾概念中。
包裝器很簡單。 這需要一個延遲,並且您要“解析”該值。 您不必傳遞價值。...我只是這樣做了,所以我們有了傳遞諾言並期待回報的想法。
function promiseWrapper(time, value) {
return new Promise(resolve => {
return setTimeout(() => resolve(`passed value: ${value}`), time);
})
}
async function first()
{
const result = await promiseWrapper(3000, 'first called');
console.log("FIRST RESULT", result)
return result
}
async function second()
{
const result = await promiseWrapper(1000, 'second called');
console.log("FIRST RESULT", result)
return result
}
// this runs each at the same time, and each function
// returns a value irrespective of the others functions. BUT
// all values are returned at the same time... ala Promise.all
async function runAllParallel() {
const results = await Promise.all([first(), second()]);
console.log(results);
}
// this is what you asked for.. only fire each function after
// the preceding one finishes.
async function runAllSerial() {
await first(),
await second();
}
//runAllParallel()
runAllSerial()
詳細介紹您的職能性質。
如果函數是同步的,則只需按順序調用: first(); second(); third();
first(); second(); third();
否則,您需要附加到異步函數的回調並按順序調用下一個函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.