我正在使用 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/