javascript - 添加实现到 Promise.resolve

标签 javascript promise es6-promise

我想创建一个小脚本来通过使用 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/

相关文章:

javascript - Mongo : find returns nothing, 也没有错误

javascript - 替换函数与 if 语句组合

javascript - 如何确保数组没有空值?

javascript - ES6 迭代器和 settimeout

javascript - 使用 Promise 进行方法链接

javascript - session 未通过 AJAX 正确发送

node.js - Q.allSettled 会失败吗?

javascript - 异常在 promise 链中被吞没

javascript - 获取模拟 : GLOBAL is not defined

javascript - 如何将日期选择器的 HTML5 表单最小限制设置为 "Check-In Date (user input)"