2017-01-11 4 views
1

thenメソッドの代わりにisValidメソッドを使用して、モデルをチェックするための小さなスクリプトを作成したいですか?Promise.resolveに実装を追加

$('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>
ここ

は、スクリプトが thenメソッドを使用しています

エラーメッセージ:

Uncaught TypeError: 'model.isValid' is not a function

私の質問:どのように私はこのケースでisValid関数を定義することができますか?

+0

あなたは解決関数内でそのチェックを行う必要があります! – callback

+0

プロミスを使用する理由は明確ではありません。あなたの質問に貼り付けなかった非同期検証はありますか? – Sergeon

+0

@Sergeon私は約束を学んでいるので。 –

答えて

1

あなたは第2の実施のために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.resolve({ 
    isValid() { 
     let isValid = $('input[type=text]').val().length > 0; 
     return isValid; 
    } 
    }); 

あなたが戻ってきていますオブジェクトはではない可\then方法が、isValid 1)にあなたは、単に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>

+0

ああ。私はあなたが意味することを理解する。 'then'メソッドなしで' isValid'メソッドを使うことはできません。ありがとう! –

0

なぜ、プロミスを使用する必要がありますか?あなたの例のよりシンプル

$('button').click(function() { 
    let isValid = $('input[type=text]').val().length > 0; 
    if (isValid) { 
    console.log('model is valid.'); 
    } 
}); 
+0

申し訳ありませんが、エラーメッセージが表示された理由を教えてください。 'model.isValidは関数ではありません。 ' –

関連する問題