2016-11-10 133 views
2

我正在使用node/express,mysql和bluebird。在異步承諾中迭代數組

我正在使用承諾進行異步數據庫調用,目前正在工作。但是現在我想迭代結果(數組)並調用函數來計算目的。

我的代碼被分成一個Controller類,它處理get/ post請求。在中間是業務邏輯的服務類,它與在數據庫中查詢的數據庫類進行對話。

現在我將只顯示我的服務類,因爲其他所有工作都很完美,我只是不知道如何運行結果數組和調用函數,它返回一個日期範圍。

'use strict'; 

var departmentDatabase = require('../database/department'); 
var moment = require('moment'); 

class DepartmentService { 
    constructor() { 
    } 

    getVacation(departmentID) { 
     return departmentDatabase.getVacation(departmentID).then(function (result) { 

      //Without promises I did this, which worked. 
      //for(var i = 0; result.length > i; i++){ 
      // var dateRange = this.getDateRange(new Date(result[i].dateFrom), new Date(result[i].dateTo)); 
      //console.log(dateRange); 
      //} 
      return result; 

     }) 

     //If I do it static, the dateRange function is successfully called 
     //But here I don´t know how to do it for the entire array. 
     //Also I don´t know, how to correctly get the result dateRange() 
     .then(result => this.dateRange(result[0].dateFrom, result[0].dateTo)) 
     //.then() Here I would need an array of all dateRanges 
     .catch(function (err) { 
      console.log(err); 
     }); 
    } 

    getDateRange(startDate, stopDate) { 
     console.log("inDateRange"); 
     console.log(startDate + stopDate); 

     var dateArray = []; 
     var currentDate = moment(startDate); 
     while (currentDate <= stopDate) { 
      dateArray.push(moment(currentDate).format('YYYY-MM-DD')) 
      currentDate = moment(currentDate).add(1, 'days'); 
     } 

     return dateArray; 
    } 
} 

module.exports = new DepartmentService(); 

希望有人能給我一個關於如何做到這一點的例子。

回答

1

在你的新代碼中,你只處理第一個結果。你可能想map

.then(result => result.map(entry => this.dateRange(entry.dateFrom, entry.dateTo))) 

因此在與舊代碼的上下文中刪除:

getVacation(departmentID) { 
    return departmentDatabase.getVacation(departmentID) 
    .then(result => result.map(entry => this.dateRange(entry.dateFrom, entry.dateTo))) 
    .catch(function (err) { 
     console.log(err); 
     // WARNING - This `catch` handler converts the failure to a 
     //   resolution with the value `undefined`! 
    }); 
} 

注意上面的警告。如果你想傳播錯誤,你需要明確地做到這一點:

.catch(err => { 
    // ...do something with it... 
    // If you want to propagate it: 
    return Promise.reject(err); 
    // Or you can do: 
    // throw err; 
}); 
+0

哇,完美!這是我需要的。 – BayLife