JavaScript resolving Promises sequentially javascript resolve promises sequentially,functional javascript resolving promises sequentially,resolve

EDIT: This is for an Electron project, with a local server spun up on the user's system. So, any concerns about what happens if multiple users attempt simultaneous access can be ignored!


My client code is generating an array of JavaScript objects, which I'm calling packets. There can be potentially infinite packets, although between 1 and 10 is the most common use-case.

I need to make API calls to a backend route, one per packet, passing a packet as an argument to each call.

However, the backend does some heavy computational work on each packet, to the point where attempting to crunch more than 2-3 packets at once crashes the server.

Is it possible to resolve Promises synchronously, such that the second Promise only fires when the first resolves, the third firing after the second, and so on?

It's my understanding that Promise.all() makes all calls simultaneously, which doesn't help me here.

(I also know that this is an anti-pattern, but for my specific set of requirements, I'm not sure what else to do)

I know this is purely abstract, but any thoughts would be appreciated!!!

Answer:1

As an alternative to an otherwise good answer, here's a really simple queue that works (work function shamelessly copied and expanded from other answer)

    // Here is the queue "creator"
    let promiseQueue = fn => {
        let q = Promise.resolve();
        return (...args) => q = q.then(() => fn(...args));
    };
    // that's it, that's the whole code for a promise queue

    // here we create a queue
    var q = promiseQueue(work);

    // simple mock asynchronous function
    function work({index, data}) {
        var duration = parseInt(Math.random() * 100) + 100;
        console.log('START JOB %s, I.E., MAKE REQUEST (will take %s) and should result with %s', index, duration, (index +1) * data);
        return new Promise(resolve => setTimeout(resolve, duration)) // mock a delay
        .then(() => ({index, result:(index + 1) * data})); // and some "processing"
    }


    // simulating two "chunks" of packets, generated a millisecond apart, but still, the sequence will be maintained
    setTimeout(() => {
        var packets = Array.from({length:10}, (_, index) => ({index, data:parseInt(Math.random() * 10000)}));
        var promises = packets.map(packet => q(packet));
        // the results in promise all are all the results of this batch of "packets"
        Promise.all(promises).then(results => console.log(results));
    }, 100);
    setTimeout(() => {
        var packets = Array.from({length:10}, (_, index) => ({index: index + 10, data:parseInt(Math.random() * 10000)}));
        var promises = packets.map(packet => q(packet));
        Promise.all(promises).then(results => console.log(results));
    }, 101);
Answer:2

the simple function to execute promises sequentially

const sequentiallyExecuting = (promises) => {
    let promise = Promise.resolve();
    promises.forEach((task) => {
        promise = promise.then((data) => {
            return task;
        })
    });

    return promise;
}
// pass array of promises to this function
sequentiallyExecuting(promises).then((data) =>{
   console.log("all requests completed sequentially");
})
Answer:3

'use strict';

// job to be done
function job(params) {
	return function () {
		console.log('job started', params);
		return new Promise(function (resolve) {
			setTimeout(function () {
				console.log('job finished');
				resolve();
			}, 1000);
		})
	}
}

// data to be processed sequentially 
var params = [
	1,
	2,
	3,
	4,
	5
];
// reduce data to Promise sequence
params.reduce(function (cum, cur) {
	return cum.then(job(cur));
}, Promise.resolve());
Answer:4

I´m using mongoose and I need to find a model name from a model instance. In one part of the code I have: const schema = new mongoose.Schema({ name: { type: String, ...

I´m using mongoose and I need to find a model name from a model instance. In one part of the code I have: const schema = new mongoose.Schema({ name: { type: String, ...

  1. there she goes model name
  2. there she goes song model name

Im using codeigniter to load a view. This view has a button to open a modal and in this modal i must load a method from another controller. To do this, i'm using ajax passing data by POST. This is my ...

Im using codeigniter to load a view. This view has a button to open a modal and in this modal i must load a method from another controller. To do this, i'm using ajax passing data by POST. This is my ...

  1. jquery ajax cross domain
  2. jquery.ajax-cross-origin.min.js
  3. jquery ajax cross domain access-control-allow-origin
  4. jquery ajax cross origin
  5. jquery ajax cross-origin request blocked
  6. jquery ajax cross domain post
  7. jquery ajax cross domain request example
  8. jquery ajax redirect to another page
  9. jquery ajax redirect to another page with data
  10. jquery ajax cross domain example

I'm trying to sort the JSON by release date, by random, by alphabetical order or by popularity. I'm not sure if the answer is on here, I checked and I can't seem to figure out if it's for me. My ...

I'm trying to sort the JSON by release date, by random, by alphabetical order or by popularity. I'm not sure if the answer is on here, I checked and I can't seem to figure out if it's for me. My ...

I try to create a new pieces page, kind of a blog style in apostrophe cms. I have trainings, trainings-widgets and trainings-pages folders. I registered them all in app.js; pieces by themselves and ...

I try to create a new pieces page, kind of a blog style in apostrophe cms. I have trainings, trainings-widgets and trainings-pages folders. I registered them all in app.js; pieces by themselves and ...

  1. apostrophe pieces pages