在异步承诺中迭代数组

Iterate over array in async promise

我正在使用 node/express、mysql 和 bluebird。

我正在使用 Promises 进行异步数据库调用,到目前为止它正在运行。但是现在我想遍历结果(数组)并调用一个函数进行计算。

我的代码被分离到一个控制器 class 中,它处理 get/ post 请求。中间是一个用于业务逻辑的服务 class,它与数据库 class 对话,后者在数据库中进行查询。

现在我将只展示我的服务 class,因为其他一切都运行良好,我只是不知道如何 运行 遍历结果数组并调用函数,returns一个日期范围。

'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();

希望有人能给我一个正确的例子。

在您的新代码中,您只处理第一个结果。你可能想要 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;
});