2016-09-24 91 views
1

這段代碼等同於是Promise.all([]),相當於promise.then()。然後,()

promise1 
    .then(() => promise2) 
    .then(() => doSomething()) 

Promise.all([ 
    promise1, 
    promise2, 
]) 
.then(() => doSomething()) 

我以爲他們是等價的,但他們做的在fortunejs和mocha應用程序中表現不一樣。以下是有關此應用程序的詳細信息


我使用fortune.js,我想編寫使用摩卡一些測試。我試圖實現的是使用beforeEach掛鉤來截斷數據庫中的表格,然後插入一些預先設定的值。所以,如果我有兩個表名爲customeruser我會做這樣的事情

beforeEach(function() { 
    return Promise.all([store.delete('user'), store.delete('customer')]) 
    .then(() => store.create('customer', { 
     id: '0987654321234567890', 
     // More data 
    })) 
    .then(() => store.create('user', { 
     id: 'qwertyuioppoiuytrewq', 
     customer: '0987654321234567890', 
     // More data 
    })); 
}); 

此代碼並不穩定,有時,有時不工作沒有我可以找到爲什麼(%左右50的成功率)

但是,如果我切換到該代碼是工作:

beforeEach(function() { 
    return store.delete('customer') 
    .then(() => store.delete('user')) 
    .then(() => store.create('customer', { 
    id: '0987654321234567890', 
    // More data 
    })) 
    .then(() => store.create('user', { 
    id: 'qwertyuioppoiuytrewq', 
    customer: '0987654321234567890', 
    // More data 
    })); 
}); 

我認爲

Promise.all([ 
    promise1, 
    promise2, 
]) 
.then(() => doSomething()) 

相當於

promise1 
    .then(() => promise2) 
    .then(() => doSomething()) 

由於store.delete回報的承諾,爲什麼我有一個不同的行爲?然後

回答

2

Promise.all([ 
    promise1, 
    promise2, 
]) 
.then(() => doSomething()) 

開始在同一時間同時執行的承諾,並呼籲()在最新完成的,而這

promise1 
    .then(() => promise2) 
    .then(() => doSomething()) 

開始與第一承諾,當這樣完成執行第二個等等。

+0

Brillant!順序不是問題,但問題是我嘗試同時訪問數據庫兩次 – ThomasThiebaud

+0

這就是all()的設計目的。您可以使用each()或map()和其他函數按順序解析promise。 – marekful

+0

非常感謝,我會做;) – ThomasThiebaud

1

不,它們不是等效的。

The docs對於Promise.all()說明,雖然返回值是輸入承諾的順序,但它們不按該順序解析。

鏈接承諾.then()解決每個承諾的順序。

+0

訂單不是問題。如果我切換訂單,問題依舊。問題是'Promise.all'在數據庫訪問存在問題時執行諾言(請參閱@marekful答案) – ThomasThiebaud

+1

我們的答案是相同的。 _resolution_的順序是問題。 –