2017-08-07 210 views
1

問題出在這裏 - 我調用一個函數,並且可以多次顯示一個對話框並等待用戶按下OK。之後 - 我想做別的事情。異步使用javascript承諾

我認爲解決方案需要使用Promise。但dialog.alert()調用的異步特性正在拋棄我。

function a() 
{ 
if (condition_ok) 
{ 
    // there could be multiple dialogs 
    // 
    for (int i = 0; i < 2; ++i) 
     dialog.alert("press ok").then (()=> { console.log("done"); }); 
    } 
} 
a(); 
// call b() after all the dialogs have been closed in a() 
b(); 
+0

'for(int i = 0;我<2; ++ i)'... int? –

+0

應該是僞代碼......這是當你在同一時間使用多種語言時發生的情況。 – dashman

回答

3

如果你在有箭頭功能的環境(你的代碼表明你做的),但不支持async/await(這是一個很好的答案通過@ guest271314),您可以使用以下代替

function a() { 
    var p = Promise.resolve(); 
    if (condition_ok) { 
     // there could be multiple dialogs 
     // 
     for (var i = 0; i < 2; ++i) { 
      p = p 
      .then(() => dialog.alert('press ok')) 
      .then(() => { 
       console.log('done'); 
      }); 
     } 
    } 
    return p; 
} 
a().then(b); 

注:每個對話框將等待前一個「關閉」,我認爲這是你的代碼打算什麼

+0

哎呀,愚蠢的錯字 –

+0

我沒有嘗試這個,因爲似乎有一些語法問題。還有,p = p呢? – dashman

+0

。然後在下一行。我有我的方式鏈接承諾 –

0

您可以使用async/awaitPromise.all()Array.prototype.map()

async function a() { 
    if (condition_ok) { 
    // there could be multiple dialogs 
    // 
    for (let i = 0; i < 2; i++) { 
     let curr = await dialog.alert("press ok"); 
     console.log("done"); 
    } 
    } 
    return 
} 
// call b() after all the dialogs have been closed in a() 
a().then(() => b(), err => console.error(err)); 
+0

第一次聽到異步/等待 - 很可能不支持。不過謝謝。 – dashman

+0

@dashman查看https://stackoverflow.com/questions/42183155/is-it-safe-to-use-async-await-now,https://caniuse.com/#search=await – guest271314

0

使用Promise.all()

let targets = [] 
for (let i = 0; i < 2; i++) { 
    targets.push(dialog.alert('press ok')) 
} 
Promise.all(targets).then(([result1, result2]) => { 
    b(); 
}) 
+0

謝謝 - 按預期工作 - 即使沒有輸入'for'循環。 – dashman

0

你所面臨的問題是,你需要等待所有你的異步alert在叫b之前完成。您可以將所有異步調用存儲在數組中,然後使用Promise.all()確保在調用b之前完成所有這些調用。這裏是你如何能做到這一點

// Faking data/objects - START 
 
const condition_ok = true; 
 
const dialog = { 
 
    alert() { 
 
    return new Promise((resolve, reject) => { 
 
     resolve("Done"); 
 
    }) 
 
    } 
 
} 
 
const b =() => { 
 
    console.log("Call b()") 
 
} 
 
// Faking data/objects - END 
 

 
function a() { 
 
    let promises = []; 
 
    if (condition_ok) { 
 
    for (let i = 0; i < 2; ++i) { 
 
     promises.push(dialog.alert("press ok").then(() => { 
 
     console.log(`Done with alert() for ${i}`); 
 
     })); 
 
    } 
 
    } 
 
    return promises; 
 
} 
 

 
Promise.all(a()).then(results => { 
 
    // call b() after all the dialogs have been closed in a() 
 
    b(); 
 
});

+0

a()返回undefined的condition_ok爲false。 – dashman

+0

你說得對。錯過了。編輯代碼。 –