javascript - 函数只返回事件

标签 javascript function events dom-events

我正在使用 console.log(openDialog()) 调用一个函数,并且 openDialog() 创建一个模态窗口,该函数仅在某些事件上返回。

我的 openDialog() 就像

function openDialog() {
  // do some html

  //
  buttonElement.onclick = function () {
    return 'some value';
  }
}

问题是当我调用 console.log(openDialog()) 时,它自动发现我的函数没有返回值,所以它只返回 undefined。我希望它等到我的函数 openDialog() 返回一些东西。

也许是 promise ?

编辑

回调就是这样吗?

function openDialog(cb) {
  // do some html

  buttonElement.onclick = function () {
    return cb('some value');
  }
}

console.log(openDialog(function (value) {
  return value;
});

最佳答案

因此,假设您正在尝试创建一个自定义的 prompt(),您必须记住我们不能同步进行。

这使用同步的 native prompt 函数:

var result = prompt("What's your name");

您不能创建这样的函数。相反,您需要使其异步:使用回调(或 promise )。

简单的回调接口(interface)

function openDialog(buttonElement, cb) {
  buttonElement.onclick = function () {
    cb('some value');
  }
}

// Open the dialog
openDialog(document.querySelector("button"), function (result) {
  // After getting the result, this will be called
  alert(result);  
});
<button>Submit</button>

promise 界面

function openDialog(buttonElement) {
  var resolve = null;
  var promise = new Promise(function (_resolve) {
    resolve = _resolve;
  });
  buttonElement.onclick = function () {
    resolve('some value');
  }
  return promise;
}

// Open the dialog
openDialog(document.querySelector("button")).then(function (result) {
  // After getting the result, this will be called
  alert(result);  
});
<button>Submit</button>


如果您还想在回调中发送错误,您只需调用 callback 函数并将错误作为第一个参数。在 Promises 案例中,使用 reject 函数:

function openDialog(buttonElement) {
  var resolve = null;
  var reject = null;
  var promise = new Promise(function (_resolve, _reject) {
    resolve = _resolve;
    reject = _reject;
  });
  buttonElement.onclick = function () {
    var name = your_name.value;
    if (!name) {
      return reject(new Error("Please enter a name in the input."));
    }
    resolve(name);
  }
  return promise;
}

// Open the dialog
openDialog(document.querySelector("button")).then(function (result) {
  // After getting the result, this will be called
  alert(result);  
}).catch(function (err) {
  alert(err.message);
});
<input id="your_name" />
<button>Submit</button>

对于回调情况,成功时调用cb(null, name),错误时调用cb(new Error("Please enter a valid name"))。然后你会这样调用它:

openDialog(document.querySelector("button"), function (err, result) {
  if (err) { return alert(err.message); }
  // After getting the result, this will be called
  alert(result);  
});

关于javascript - 函数只返回事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39684101/

相关文章:

未检查 C++ 返回语句

function - 带有前缀参数和用户输入作为可选参数的 ELISP 交互函数

python - python 的可变长度参数 (*args) 会在函数调用时扩展生成器吗?

events - Google Maps API v3 'dragend' 事件在 map 完成滑动之前触发

javascript - 在 Node.js 中编写可重新调度的 cron 作业

选择标签上的 JavaScript 更改功能

javascript - 别处点击事件?

javascript - 如何在单击时将新的输入行添加到表中?

javascript - 我需要 slider 上的自定义范围,例如 1,2,3,4,5,10,15,20,25..... 我们能实现这一点吗?

JavaScript 模块模式和拖放 API