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();
希望有人能給我一個關於如何做到這一點的例子。
哇,完美!這是我需要的。 – BayLife