How Can I Properly Call A List Of Async Functions In Order?
I am attempting to write a 'robocopy /mir' like function within Node.js and cannot seem to wrap my head around how to properly execute several async functions in order. Some backgr
Solution 1:
Maybe something like that will do the trick :
var $j = function(val, space) {
returnJSON.stringify(val, null, space || '')
}
var log = function(val) {
document.body.insertAdjacentHTML('beforeend', '<div><pre>' + val + '</div></pre>')
}
var files = '12345'.split('').map(function(v) {
return {
name: 'file_' + v + '.js',
load: function() {
var cur = this;
var pro = newPromise(function(resolve, reject) {
log('loading : ' + cur.name);
// we simualate the loading stuffsetTimeout(function() {
resolve(cur.name);
}, 1 * 1000);
}).then( function( val ) {
// once loaded log('loaded : ' + val);
return val;
});
return pro;
}
};
});
files.reduce(function(t, v) {
t.promise = t.promise.then(function(){
return v.load();
});
return t;
}, {
promise: Promise.resolve(1)
});
Solution 2:
Use async.eachSeries
on arrays, or async.forEachOfSeries
on objects.
Looping an object
varasync = require('async');
var filesObject = {'file/path/1': {}, 'file/path/2': {}};
async.forEachOfSeries(filesObject, copyFileFromObj, allDone);
functioncopyFileFromObj(value, key, callback) {
console.log('Copying file ' + key + '...');
callback(); // when done
}
functionallDone(err) {
if (err) {
console.error(err.message);
}
console.log('All done.');
}
Looping an array
varasync = require('async');
var filesArray = ['file/path/1', 'file/path/2'];
async.eachSeries(filesArray, copyFile, allDone);
functioncopyFile(file, callback) {
console.log('Copying file ' + file + '...');
callback(); // when done
}
functionallDone(err) {
if (err) {
console.error(err.message);
}
console.log('All done.');
}
Working example here: https://tonicdev.com/edinella/sync-loop-of-async-operations
Post a Comment for "How Can I Properly Call A List Of Async Functions In Order?"