From b010dc28d26ae98bb9e690037a77ab936d73112f Mon Sep 17 00:00:00 2001 From: Borewit Date: Thu, 7 Jun 2018 21:48:45 +0200 Subject: [PATCH 1/2] Avoid promise resolve results are ending up as error objects in callback handler. Reference: issue: webtorrent/webtorrent-desktop#1417 --- src/renderer/lib/state.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/renderer/lib/state.js b/src/renderer/lib/state.js index 8fc89a4f..23b5802a 100644 --- a/src/renderer/lib/state.js +++ b/src/renderer/lib/state.js @@ -133,19 +133,19 @@ function setupStateSaved (cb) { const tasks = [] - config.DEFAULT_TORRENTS.map(function (t, i) { + config.DEFAULT_TORRENTS.map((t, i) => { const infoHash = saved.torrents[i].infoHash - tasks.push(function (cb) { + tasks.push(cb => { cpFile( path.join(config.STATIC_PATH, t.posterFileName), path.join(config.POSTER_PATH, infoHash + path.extname(t.posterFileName)) - ).then(cb).catch(cb) + ).then(() => cb()).catch(cb) }) - tasks.push(function (cb) { + tasks.push(cb => { cpFile( path.join(config.STATIC_PATH, t.torrentFileName), path.join(config.TORRENT_PATH, infoHash + '.torrent') - ).then(cb).catch(cb) + ).then(() => cb()).catch(cb) }) }) From 5cdb3d059c3d5e3c86055a933d84f4e9a99a10a6 Mon Sep 17 00:00:00 2001 From: Borewit Date: Sat, 9 Jun 2018 14:54:24 +0200 Subject: [PATCH 2/2] #1417: Simplify code - use forEach instead of map (because return value was ignored) - use Promise.all instead of parallel, because tasks are already Promise based. Fewer callbacks. --- src/renderer/lib/state.js | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/src/renderer/lib/state.js b/src/renderer/lib/state.js index 23b5802a..c005aa0f 100644 --- a/src/renderer/lib/state.js +++ b/src/renderer/lib/state.js @@ -113,7 +113,6 @@ function setupStateSaved (cb) { const cpFile = require('cp-file') const fs = require('fs') const parseTorrent = require('parse-torrent') - const parallel = require('run-parallel') const saved = { prefs: { @@ -133,26 +132,25 @@ function setupStateSaved (cb) { const tasks = [] - config.DEFAULT_TORRENTS.map((t, i) => { + config.DEFAULT_TORRENTS.forEach((t, i) => { const infoHash = saved.torrents[i].infoHash - tasks.push(cb => { + tasks.push( cpFile( path.join(config.STATIC_PATH, t.posterFileName), path.join(config.POSTER_PATH, infoHash + path.extname(t.posterFileName)) - ).then(() => cb()).catch(cb) - }) - tasks.push(cb => { + ) + ) + tasks.push( cpFile( path.join(config.STATIC_PATH, t.torrentFileName), path.join(config.TORRENT_PATH, infoHash + '.torrent') - ).then(() => cb()).catch(cb) - }) + ) + ) }) - parallel(tasks, function (err) { - if (err) return cb(err) - cb(null, saved) - }) + Promise.all(tasks) + .then(() => cb(null, saved)) + .catch(err => cb(err)) function createTorrentObject (t) { // TODO: Doing several fs.readFileSync calls during first startup is not ideal