Conjuring JQuery Deferred with monadic incantations

前端 未结 3 984
名媛妹妹
名媛妹妹 2021-01-13 06:34

Inspired by this (excellent) discussion of using Promises in javascript, I\'m trying to work out how I could use Deferred to chain together async and non-async functions, to

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-13 06:44

    I think the way that you'd turn a value into a Promise is to just "pre-succeed" the Deferred:

    function v2p(value) {
      var rv = $.Deferred();
      rv.resolveWith(null, [value]);
      return rv.promise();
    }
    

    Now passing a function to ".done()" will result in the function being immediately called with the value.

    v2p("hello").done(function(value) { alert(value); });
    

    would immediately alert "hello".

提交回复
热议问题