2016-04-15 97 views
0

針說我做錯了什麼。我需要一些幫助來搞清楚它是什麼。Javascript承諾:然後()的不同步

考慮下面的代碼(我的問題的簡化版本):

function testTimer(time, msg,resolve){ 
console.log(arguments.callee.name); 
window.setTimeout(
       function() { 
        console.log("MSG:", msg); 
        if(resolve !== undefined) 
         resolve(1); 
       }, time * 1000); 
} 

new Promise(function(resolve, reject) { 
    testTimer(1, 'ONE', resolve); 
}).then(function(resolved){testTimer(9, 'TWO');}, function(rejected){alert("Rejected!", reject)}) 
.then(function(resolved){testTimer(1, 'THREE'); }, function(rejected){alert("Rejected!", reject)}); 

預期的輸出是:

ONE 
TWO 
THREE 

相反由於第一然後要求9秒執行和第二然後需要1秒執行我得到:

ONE 
THREE 
TWO 

問題很簡單:如何我可以得到當時的等待彼此嗎?

謝謝!

回答

0

你需要以返回超時火災後只能解決一個承諾:

function testTimer(time, msg,resolve) { 
    console.log(arguments.callee.name); 
    window.setTimeout(function() { 
     console.log("MSG:", msg); 
     if(resolve !== undefined) { 
      resolve(1); 
     } 
    }, time * 1000); 
} 

new Promise(function(resolve, reject) { 
     testTimer(1, 'ONE', resolve); 
    }).then(
     function(resolved){ 
      // here we return a promise - that is resolved by testTimer 
      // function. Notice that I'm passing a resolve function into it 
      return new Promise(function(resolve) { 
       testTimer(9, 'TWO', resolve); 
      }); 
     }, 
     function(rejected){ 
      alert("Rejected!", reject) 
     } 
    ) 
    .then(
     function(resolved){testTimer(1, 'THREE'); }, 
     function(rejected){alert("Rejected!", reject)} 
    ); 

它是如何工作的:testTimer功能爲你定義了它 - 接受一個回調,因爲這是成爲第三個參數定時器啓動後調用。我們用這個來解決我們在第二步中設定的嵌套承諾。所以第三步只有在第二步解決後纔會發生,這發生在計時器中,所以訂單保持如預期的那樣。