문제

(이 질문은 실제로 언어로 제한되지 않으므로 다른 언어로도 솔루션을 제출하십시오.)

JavaScript에서 이와 같은 글을 쓸 수 있는지 궁금합니다.

// Wait 3 seconds and then say our message in an alert box
wait(3).then(function(){alert("Hello World!");});

전통적인 방법이 글을 쓰는 곳

// Wait 3 seconds and then say our message in an alert box
setTimeout(function(){alert("Hello World!");}, 3000);

이것이 멍청한 질문이라면 죄송합니다 : p

도움이 되었습니까?

해결책

쉽게 쓸 수 있습니다.

function wait(delay) {
  return {
    then: function (callback) {
      setTimeout(callback, delay*1000);
    }
  };
}

wait(3).then(function(){alert("Hello World!");});

깊이 가고 싶다면 읽어 보는 것이 좋습니다. 카레 그리고 부분 기능 응용 프로그램, 그 주제는 정말 흥미 롭습니다.

다른 팁

폐쇄없이 다른 버전 :

function wait(seconds) {
    if(this instanceof wait)
        this.delay = seconds;
    else return new wait(seconds);
}

wait.prototype.then = function(callback) {
    setTimeout(callback, this.delay * 1000);
};

더 많은 코드를 사용하면 기능을 반복적으로 호출 할 수도 있습니다.

function wait(seconds) {
    if(this instanceof wait)
        this.delay = seconds;
    else return new wait(seconds);
}

wait.prototype.then = function(callback) {
    setTimeout(callback, this.delay * 1000);
    return this;
};

wait.prototype.wait = function(seconds) {
    this.delay += seconds;
    return this;
};

var start = new Date;
function alertTimeDiff() {
    alert((new Date - start)/1000);
}

wait(1).then(alertTimeDiff).wait(3).then(alertTimeDiff);

체인은 오히려 하나의 객체에서 여러 메소드를 실행하는 데 사용됩니다. 따라서 기능을 객체로 고려하고 시간 초과를 설정합니다.

Function.prototype.callAfter = function(delay) {
    setTimeout(this, delay*1000);
};

(function(){alert("Hello World!");}).callAfter(3);

JavaScript를 수행하면 예, 메소드 체인을 수행 할 수 있습니다.

인기있는 JavaScript 프레임 워크 중 일부가이를 수행합니다. jQuery 일반적으로 값을 반환하지 않는 함수에 대해 jQuery 객체를 반환하여이를 수행합니다.

방금 썼습니다 작은 도우미 다소 일관된 방식으로 이와 같은 API를 만들려면 아마도 당신이 좋아할 것입니다.

// > npm i mu-ffsm # install node dependency
var mkChained = require('mu-ffsm');

아이디어는 초기 유형 상태를 가진 유창한 빌더를 건설한다는 것입니다. S 입력 기능을 호출하여. 그런 다음 각 체인 호출은 상태를 새로운 상태로 전환합니다.

많은 통화를 체인하면 얻은 값은 함수로 실행될 수 있으며, 이는 해당 상태에서 값을 구성하기 위해 EXIT를 호출하고 통과하는 옵션을 구성합니다.

  • 진입 : *. s
  • 전환 : (s s *) ⟶ s
  • 종료 : S ⟶ ( * ⟶ *)

예를 들어

var API = mkChained({
  0:    function(opt)    {return ;/* create initial state */},
  then: function(s, opt) {return s; /* new state */},
  whut: function(s, opt) {return s; /* new state */},
  1:    function(s, opt) {return ;/* compute final value */}
});

그래서 0, 1 입력, 종료 함수입니다. 다른 모든 기능은 내부 상태를 전환합니다. 모든 기능은 논쟁을 취할 수 있습니다. opt

우리는 새로 제작 된 API 인스턴스를 만듭니다.

var call = API() // entry
   .whut()       // transition
   .then()       // transition
   .whut();      // transition

그리고 그것을 부릅니다

var result0 = call() // exit
  , result1 = call() // exit

(작은)를보세요 원천 이것이 어떻게 구현되는지 확인합니다.

추신. 이 답변을 사용하여 문서 업데이트 : d

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top