我想创建一个小脚本来通过使用 isValid
方法而不是 then
方法来检查模型是否有效。
这是使用 then
方法的脚本:
$('button').click(function () {
let model = Promise.resolve({
then(x, y) {
let isValid = $('input[type=text]').val().length > 0;
x(isValid);
}
});
model.then(isValid => console.log(isValid));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
<button>check</button>
我的目标:
if (model.isValid()) {
console.log('model is valid.');
}
我已经尝试过:
$('button').click(function () {
let model = Promise.resolve({
isValid() {
let isValid = $('input[type=text]').val().length > 0;
return isValid;
}
});
if (model.isValid()) {
console.log('model is valid.');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
<button>check</button>
错误消息:
Uncaught TypeError: 'model.isValid' is not a function
我的问题:在这种情况下如何定义 isValid
函数?
最佳答案
您的第二个实现会出现运行时错误,因为 Promise.resolve返回:
a Promise object that is resolved with the given value. If the value is a thenable (i.e. has a "then" method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise the returned promise will be fulfilled with the value.
所以,如果你这样定义 Promise:
Promise.resolve({
isValid() {
let isValid = $('input[type=text]').val().length > 0;
return isValid;
}
});
您返回的对象not thenable(它没有 then
方法,但有 isValid
一),所以你不能简单地执行 model.isValid()
但你必须:
$('button').click(function () {
let model = Promise.resolve({
isValid() {
let isValid = $('input[type=text]').val().length > 0;
return isValid;
}
});
model.then(res => {
if (res.isValid()) {
console.log('model is valid.');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
<button>check</button>
关于javascript - 添加实现到 Promise.resolve,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41589471/