Sample code to execute promises in sequence

Does anyone have sample code that executes an arbitrary length series of promises in order, each one running after the previous one finished? I’ve tried two different approaches based on code that I found on stackoverflow and other places and I just can’t get it to work. Note I am running this on the client side. In both cases I create an array of method invocations, where each invocation returns a Promise. For example,

let pf = [];
    clients.forEach( client => {
        pf.push(getMembershipInfoAndUpdateCache(client));
    })

where the function is:


function getMembershipInfoAndUpdateCache(client) {
 return new Promise( function(resolve, reject) { ...

In one case I use array.reduce:

function runPromiseInSequence(arr, input) {
 return arr.reduce(
    (promiseChain, currentFunction) => promiseChain.then(currentFunction),
    Promise.resolve(input)
  );
}

In the other case I used the .then() method as follows:

   let res = Promise.resolve();
    pf.forEach(function(f) {
        res = res.then(f);
    });

In both cases they return immediately and my calling function goes to the next .then() in the sequence without waiting. Does anyone have working code they can share? Many thanks!

Have a read here about working with asynchronous code and using promises.
https://support.wix.com/en/article/corvid-working-with-promises

This is more advanced than the scenarios described in that article.

I didn’t say it was an answer to your question, it was just a link to the Wix Support page that tells you about working with asynchronous code within Wix Corvid, so yes it won’t be advanced as your needs.

A Google search for executing promises in series returns a good number of very useful articles.

Indeed, and I’ve read quite a few of them. They seemed to fall into two camps, 1) use reduce with promiseChain, and 2) code the sequence directly as in my second example where each result is fed to the next .then. I should think at least one would work, but neither does. So either the problem is between chair and keyboard (certainly possible, I’m relatively new to javascript but have decades of experience with many other languages), or the problem is in the framework somehow (running on the client not node.js, or something else). I can address both problems by asking whether anybody has a sample that works on wix.

To add to previous reply, there are some online references that use async/await which I would prefer to avoid because I’m trying to stick to using Promises directly. Also the two patterns I’ve seen so far both rely on the use of a promise factory.