尝试使用promise和传递参数来获取工作javascript对话框

时间:2016-11-02 21:42:03

标签: javascript parameters promise

我已经阅读/尝试了“使用承诺”部分:How do I return the response from an asynchronous call?但该示例不包含参数(但它似乎在下面的代码中正常传递),当我添加类似代码时它也不起作用代码(如下所示)。我没有遇到任何其他事情让我接近代码工作。基本上'callingFunction'在onLoad期间被调用,需要将参数传递给myDialog并在继续警报之前等待用户响应(在此简化示例中)。它现在的方式向我显示“开始”和“结束”警报,然后我看到对话框。当我点击任一按钮(仅限第一次)时,我会看到'oops'。因此代码目前不等待承诺传递或正确确认解析值。如何解决这个问题?

function myDialog(question) {
 return new Promise(function(resolve, reject) {

    var box = document.createElement('div');  
    box.style.position = "absolute";
    box.style.top = "300px";
    box.style.left = "300px";
    box.style.width = "200px";
    box.style.height = "100px";

    var text = document.createTextNode(question);
    text.margin = "20px";
    box.appendChild(text);

    var button_yes = document.createElement("button");
    button_yes.innerHTML = "Yes";
    button_yes.onclick = function() { resolve(true); }
    box.appendChild(button_yes);

    var button_no = document.createElement("button");
    button_no.innerHTML = "No";
    button_no.onclick = function() { resolve(false); }
    box.appendChild(button_no);

    window.parent.document.body.appendChild(box);
 })
}

function callingFunction(question) {
   alert('start');
   myDialog(question).then(function(v) {
     window.parent.document.body.removeChild(box); 
     if (v == true) {
            alert('true selected');
       }else{
            alert('false selected');
       }
   }).catch(function(v) {
       alert('oops');
   });
   alert('end');
}

1 个答案:

答案 0 :(得分:0)

  

因此代码当前没有等待承诺传递或正确确认解析值。

实际上是。尝试提醒/记录v值以查看罪魁祸首。您将收到一条错误消息,指出行

中未定义box
window.parent.document.body.removeChild(box);

这完全准确 - 您的box变量的范围限定为myDialog中的promise回调。你可以使用

function myDialog(question) {
  return new Promise(function(resolve, reject) {
    var container = window.parent.document.body
    var box = document.createElement('div');  
    box.style.position = "absolute";
    box.style.top = "300px";
    box.style.left = "300px";
    box.style.width = "200px";
    box.style.height = "100px";

    var text = document.createTextNode(question);
    text.margin = "20px";
    box.appendChild(text);

    var button_yes = document.createElement("button");
    button_yes.textContent = "Yes";
    button_yes.onclick = function() {
      resolve(true);
      container.removeChild(box);
    };
    box.appendChild(button_yes);

    var button_no = document.createElement("button");
    button_no.textContent = "No";
    button_no.onclick = function() {
      resolve(false);
      container.removeChild(box);
    };
    box.appendChild(button_no);

    container.appendChild(box);
  });
}

function callingFunction(question) {
  alert('start');
  myDialog(question).then(function(v) {
    alert(v+' selected');
  }).catch(function(e) {
    alert('something went wrong: '+e);
  });
}