Yakov Fain
Yakov Fain

Reputation: 12378

ECMAScript 6 Chaining Promises

I'm trying to chain promises, but the second one doesn't call the resolve function. What do I do wrong?

function getCustomers(){

  let promise = new Promise((resolve, reject) => {
      console.log("Getting customers");
      // Emulate an async server call here
      setTimeout(() => {
        var success = true;
        if (success) {
          resolve( "John Smith"); // got the customer
        } else {
          reject("Can't get customers");
        }
      }, 1000);

     }
  );
  return promise;
}

function getOrders(customer) {

  let promise =  new Promise((resolve, reject) => {
      console.log("Getting orders");
      // Emulate an async server call here
      setTimeout(() => {
        var success = true;
        if (success) {
          resolve("Order 123"); // got the order
        } else {
          reject("Can't get orders");
        }
      }, 1000);

     }
  );
  return promise;
}

getCustomers()
  .then((cust) => getOrders(cust))
  .catch((err) => console.log(err));

console.log("Chained getCustomers and getOrders. Waiting for results");

The code prints "Getting orders" from the second function, but doesn't print "Order 123":

Getting customers Chained getCustomers and getOrders. Waiting for results Getting orders

Update. I wanted to insert the print on the console between chained methods that return promises. I guess something like this is not possible:

getCustomers()
  .then((cust) => console.log(cust))  //Can't print between chained promises?
  .then((cust) => getOrders(cust))  
  .then((order) => console.log(order))
  .catch((err) => console.error(err));

Upvotes: 3

Views: 1648

Answers (2)

Evalds Urtans
Evalds Urtans

Reputation: 6694

Here is a code example for Sequential execution for node.js using ES6 ECMAScript. Maybe somebody finds it useful. http://es6-features.org/#PromiseUsage https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise

var soapClient = easysoap.createClient(params);

//Sequential execution for node.js using ES6 ECMAScript
console.log('getAllFunctions:');
soapClient.getAllFunctions()
    .then((functionArray) => {
        return new Promise((resolve, reject) => {
            console.log(functionArray);
            console.log('getMethodParamsByName:');
            resolve();
        });
    })
    .then(() => {
        return soapClient.getMethodParamsByName('test1'); //will return promise
    })
    .then((methodParams) => {
        console.log(methodParams.request); //Console log can be outside Promise like here too
        console.log(methodParams.response);
        console.log('call');

        return soapClient.call({ //Return promise
            method: 'test1',
            params: {
                myArg1: 'aa',
                myArg2: 'bb'

            }
        });
    })
    .then((callResponse) => {
        console.log(callResponse);  // response data as json
        console.log('end');
    })
    .catch((err) => {
        throw new Error(err);
    });

Upvotes: 0

Bergi
Bergi

Reputation: 664195

You want to chain a success handler (for your resolve result "Order 123"), not an error handler. So use then instead of catch :-)

getCustomers()
  .then(getOrders)
  .then((orders) => console.log(orders))
  .catch((err) => console.error(err));

None of the promises was rejected, so the console.log(err) in your code was never called.

I wanted to insert the print on the console between chained methods that return promises. I guess something like this is not possible:

getCustomers()
  .then((cust) => console.log(cust))  //Can't print between chained promises?
  .then((cust) => getOrders(cust))

Yes it is possible, but you are intercepting a chain here. So the second then callback actually is not called with cust, but with the result of the first then callback - and console.log returns undefined, with which getOrders will get some problems.

You'd either do

var customers = getCustomers();
customers.then(console.log);
customers.then(getOrders).then((orders) => …)

or simpler just

getCustomers()
  .then((cust) => { console.log(cust); return cust; })
  .then(getOrders)
  .then((orders) => …)

Upvotes: 6

Related Questions