Hahazhu

Javascript Promise Pattern

The following is the core concept to javascript Asychnoous Promise Pattern, you can extend it a little bit to realize the starndard API: .when(),.then(),.resolved(),.reject()
This is just a mock.
function Ajax(promise)
{
    var result=promise||{};
    setTimeout(function(){
	result.id="_id";
    },5000);// 5 seconds is mocking the network latency
    return result;
}

function Ajax2(promise)
{
    var result=promise||{};
    setTimeout(function(){
	result.name="Ajax2";
    },5000);// 5 seconds is mocking the network latency
    return result;
}

var promiseResult=Ajax();
setTimeout(function(){
  console.log(promiseResult.id);
},6000);

var promiseResult2=Ajax2(promiseResult);

setInterval(function(){
  console.log(promiseResult2.id+"  "+promiseResult2.name);// now the result from the first Ajax has been deffered until the Ajax2 has been finished.
},6000);

 The following is the result from Firebug:



posted @ 2013-10-31 09:38  hahazhu  阅读(298)  评论(0)    收藏  举报