ams
ams

Reputation: 91

Returning promise from a promise handler

I have two functions which are async and returning promises, output of first one has to be fed to the second one and this has to be wrapped in a third function. The caller module calls the third function and doesnt have to know that there are 2 functions internally. The caller code is able to catch all rejections but it doesnt print the resolved value.

What is wrong in the code?

function firstfn(x) {
  return new Promise(function(resolve, reject) {
    if (x === 0)
      reject(new Error("not a valid num"));
    else {
      setTimeout(function() {
        console.log("successfully resolving1");
        resolve(x * 2);
      }, 500);
    }

  });
}

function secondfn(y) {
  return new Promise(function(resolve, reject) {
    if (y === 100) reject(new Error("reject from 2"));
    else {
      setTimeout(function() {
        console.log("successfully resolving2");
        resolve(y + 2);
      }, 500);
    }

  });
}

function getsecondfn(y) {
  firstfn(y)
    .then(function(response) {
      return secondfn(response);
    })
}

function caller(inp) {
  getsecondfn(inp)
    .then(res => {
      console.log(res);
    })
    .catch(function(err) {
      console.log(err);
    })
}

caller(2);

The above code doesnt print 6 but correctly rejects when value is either 0 or 50.

Upvotes: 1

Views: 486

Answers (1)

Pengyy
Pengyy

Reputation: 38191

The problem is caused by getsecondfn since you didn't return a Promise in it (means then block at caller function won't trigger).

Refer below fixed demo:

function firstfn(x) {
  return new Promise(function(resolve, reject) {
    if (x === 0)
      reject(new Error("not a valid num"));
    else {
      setTimeout(function() {
        console.log("successfully resolving1");
        resolve(x * 2);
      }, 500);
    }

  });
}

function secondfn(y) {
  return new Promise(function(resolve, reject) {
    if (y === 100) reject(new Error("reject from 2"));
    else {
      setTimeout(function() {
        console.log("successfully resolving2");
        resolve(y + 2);
      }, 500);
    }

  });
}

function getsecondfn(y) {
  return firstfn(y)
    .then(function(response) {
      return secondfn(response);
    });
}

function caller(inp) {
  getsecondfn(inp)
    .then(res => {
      console.log(res);
    })
    .catch(function(err) {
      console.log(err);
    })
}

caller(2);

Upvotes: 3

Related Questions