2017-08-26 25 views
0

我在JavaScript中的新手,我有點堅持與異步的方式執行JS代碼...建設項目的數組中的異步過程

這裏是我的代碼:

var marketPlaces = [] 
    body.rows.forEach(function(doc) { 
    marketPlacesDB.get(doc.id, function(err, body){ 
     if (err) { 
     callback(err, null) 
     } else { 
     console.log("Ajout d'une marketplace") 
     marketPlaces.push({id: body._id, name: body.name}) 
     } 
    }) 
    }) 

    console.log("Retour des résultats") 
    callback(null, { marketPlaces: marketPlaces }) 

body.rows是一個數組,其中包含我想要在marketPlaces數組中返回的對象的ID。對於每個元素,我需要向數據庫發出一個新請求以獲取對象的詳細信息(這裏只是「名稱」)。

結果是一個空數組,因爲foreach循環在get函數的回調返回之前結束。

我不知道如何使這個「同步」。

感謝您的回答。 Philippe。

+0

什麼數據庫您使用的?它可能有一個承諾界面,可以使'Promise.all()'更容易。 – jfriend00

+1

一旦你使用'marketPlacesDB.get(doc.id,function(err,body){...')進入異步(延遲)時間線,除非你有時間機器讓你你需要在這個函數中做所有事情(包括新的異步調用) – Redu

回答

0

如果他們沒有給你同步API,你不能。

但您仍然可以通過添加大回調使其「同步」。 (我是一個非英語爲母語,我應該用什麼說不上來這裏詞)

let counter = 0; 
const max = marketPlacesDB.getLength(); // base on the real situation 
function regularCallback() { 
    /* your callback */ 
    if(++counter == max) 
     bigCallback(); 
}; 
function bigCallback() { 
    // continue on your original work 
} 
0

你不能讓它同步,如果marketPlaceDb沒有提供API。但是,你可以把它與異步版本工作太:

var async = require('async') 

function getMarketPlaces(callback) { 
    var marketPlaces = [] 

    async.eachSeries(body.rows, doc, function (next) { 
     marketPlacesDB.get(doc.id, function(err, body){ 
      if (err) { 
       next(err, null) // finish async operation 
      } else { 
       marketPlaces.push({id: body._id, name: body.name}) 
       next() // go next iteration 
      } 
     }) 
    }, function (err) { 
     // eachSeries done 
     // here is marketPlaces 
     console.log("Retour des résultats") 
     callback(err, { marketPlaces: marketPlaces }) 
    }) 

} 

getMarketPlaces(console.log) 

我用「異步」庫從NPM和eachSeries方法異步遍歷數組。

+0

你好Ozgur,它似乎是你真正理解我的問題的人;-)(我在引號之間加上了「同步」;-)) 。但是你的代碼不能直接使用。我張貼實際答案。 –

0

感謝Ozgur使用異步庫似乎是最優雅的方式來回答我的問題。

正確的代碼是:

var marketPlaces = [] 

async.eachOfSeries(body.rows, function (item, key, next) { 
    marketPlacesDB.get(item.id, function(err, body){ 
     if (err) { 
      next(err, null) 
     } else { 
      marketPlaces.push({id: body._id, name: body.name}) 
      next() 
     } 
    }) 
}, function (err) { 
    console.log("Retour des résultats") 
    callback(err, { marketPlaces: marketPlaces }) 
})