ffxsam
ffxsam

Reputation: 27793

Queuing asynchronous operations via Promises

I found one article that kind of explains how to queue up asynchronous operations, but it's rather vague in that it says if you return a "promise-like" object from a then function, it will make the next then wait for it to complete. I don't know what "promise-like" means, so I took a stab at this (see code below), and it works, but I'm not sure if this is the correct way to go about doing this or not.

let promise = new Promise(function (resolve, reject) {
  someAsyncOperation(function () {
    resolve({done: true});
  });
});

promise.then(function (val) {
  return new Promise(function (resolve, reject) {
    anotherAsyncOperation(function () {
      resolve({doneAgain: true});
    });
  });
}).then(function (val) {
  // This only occurs after the anotherAsyncOperation is done
});

Upvotes: 0

Views: 82

Answers (1)

TbWill4321
TbWill4321

Reputation: 8676

Yes, your code should function to create a promise that waits until anotherAsyncOperation is done.

let promise = new Promise(function(resolve, reject) {
    console.log('1');
    someAsyncOperation(function() {
        resolve({ done: true });
    });
}).then(function(val) {
    // val == { done: true }
    return new Promise(function(resolve, reject) {
        console.log('2');
        anotherAsyncOperation(function() {
            resolve({ doneAgain: true });
        });
    });
}).then(function(val) {
    // val == { doneAgain: true }
    console.log('3');
});

What @Amit means is that you can create "Promisified" versions of a callback-style async operation.

function promisify( operation ) {
    return function( ) {
        return new Promise(function(resolve, reject) {
            operation(function( err, val ) {
                if (err) reject(err);
                else resolve(val);
            });
        });
    };
}

var someAsyncOp = promisify( someAsyncOperation );
var anotherAsyncOp = promisify( anotherAsyncOperation );

console.log('1');
var promise = someAsyncOp()
    .then(function( val ) {
        console.log('2');
        return anotherAsyncOp();
    })
    .then(function( val ) {
        console.log('3');
    });

Note, there are promise libraries with much better promisify functions than that one I showed. Please use one of those.

Upvotes: 1

Related Questions