从承诺处理程序返回承诺

时间:2018-02-08 01:49:15

标签: javascript es6-promise

我有两个函数,它们是异步和返回的promise,第一个的输出必须被送到第二个,这必须包含在第三个函数中。调用者模块调用第三个函数,并且不必知道内部有2个函数。调用者代码能够捕获所有拒绝,但它不会打印已解析的值。

代码有什么问题?

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);

上面的代码不打印6但是当值为0或50时正确拒绝。

1 个答案:

答案 0 :(得分:2)

问题是由getsecondfn引起的,因为您没有在其中返回Promise(意味着then阻止caller功能赢了,不会触发)。

参考下面的固定演示:



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);




相关问题