node.js - For loop in promise.then()? -
i need iterate between 2 values , create/touch files (i/o) on each iteration.
i'm using fs-promise module asynchronously:
const path = require('path'); const fsp = require('fs-promise'); function addpages(startat, pages, mode) { let htmlext = mode.html; let cssext = mode.css; fsp.readfile(path.join('.', 'templates', 'body.html'), { encoding: 'utf-8' }) .then((content) => { // return promise.all(() => {}).then().catch(); // this. (let = startat, endat = startat + pages; < endat; i++) { console.log(i); fsp.writefile(path.join('.', 'manuscript', `page-${i}`, `style.${cssext}`), '') .then(() => { console.log('yay!') }) .catch(console.log.bind(console)); // fsp.writefile(path.join('.', 'manuscript', `page-${i}`, `style.${cssext}`), '') // .then((i, templatehtml) => { // fsp.writefile(path.join('.', 'manuscript', `page-${i}`, `body.${htmlext}`), content); // }) // .catch((err) => { // console.log.bind(console); // }); } }) .catch((err) => { if (err) return error('couldn\'t create pages', err); });
now did read promises.all([array of promises])
way go looping inside then()
scope, question why/how?
i'm unable wrap head around why for-loop
doesn't execute before context moves out of promised then() scope, , how should expected outcome.
const path = require('path'); const fsp = require('fs-promise'); function addpages(startat, pages, mode) { let htmlext = mode.html; let cssext = mode.css; return fsp.readfile(path.join('.', 'templates', 'body.html'), { encoding: 'utf-8' }) .then((content) => { var pendingwrites = []; (let = startat, endat = startat + pages; < endat; i++) { let filename = path.join('.', 'manuscript', `page-${i}`, `style.${cssext}`); let thiswrite = fsp.writefile(filename, ''); pendingwrites.push(thiswrite); } return promise.all(pendingwrites); }) .catch((err) => { // either recover error or rethrow console.log("could not add pages: ", err); throw err; }); }
as elaborated in comments, resist temptation introduce none-functional .catch()
handlers promise chain.
non-functional means in case: not recover error and not rethrow error. catch handler not throw marks error handled, i.e. returns resolved promise, not rejected one. makes proper error handling later in promise chain impossible. it's bad practice , unhelpful.
if want log error, log , rethrow it. if have recovered error , subsequent code unimpeded, don't rethrow.
Comments
Post a Comment