javascript - Iterate over array in async promise -
i´m working node/ express, mysql , bluebird.
i´m using promises make async database call, working far. want iterate on result (array) , call function calculation purpose.
my code separated controller class, handles get/ post
request. in middle service class business logic, talks database class queries in database.
for show service class, because else working perfectly, don´t know how run on result array , call function, returns daterange.
'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 did this, worked. //for(var = 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 static, daterange function called //but here don´t know how entire array. //also don´t know, how correctly result daterange() .then(result => this.daterange(result[0].datefrom, result[0].dateto)) //.then() here need array of 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();
hope can give me example on how right.
in new code, you're handling first result. want map
:
.then(result => result.map(entry => this.daterange(entry.datefrom, entry.dateto)))
so in context old code removed:
getvacation(departmentid) { return departmentdatabase.getvacation(departmentid) .then(result => result.map(entry => this.daterange(entry.datefrom, entry.dateto))) .catch(function (err) { console.log(err); // warning - `catch` handler converts failure // resolution value `undefined`! }); }
note warning in above. if want propagate error, need explicitly:
.catch(err => { // ...do it... // if want propagate it: return promise.reject(err); // or can do: // throw err; });
Comments
Post a Comment