使用javascript Promise异步

时间:2017-08-07 02:43:55

标签: javascript if-statement promise

这就是问题所在 - 我调用了一个函数,并且可以选择多次显示一个对话框并等待用户按OK。之后 - 我想做点别的事。

我认为解决方案需要使用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();

4 个答案:

答案 0 :(得分: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);

注意:每个对话框都会等待前一个“关闭”,我认为这是你的代码所期望的

答案 1 :(得分: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));

答案 2 :(得分: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();
})

答案 3 :(得分:0)

您遇到的问题是,在调用alert之前,您需要等待所有您的异步b。您可以将所有异步调用存储在一个数组中,然后使用Promise.all()确保在调用b之前完成所有这些调用。这是你如何做到的

&#13;
&#13;
// 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();
});
&#13;
&#13;
&#13;