首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从promise处理程序返回promise

从promise处理程序返回promise
EN

Stack Overflow用户
提问于 2018-02-08 09:49:15
回答 1查看 196关注 0票数 0

我有两个函数,这是异步和返回承诺,第一个的输出必须提供给第二个,这必须被包装在第三个函数。调用者模块调用第三个函数,而不必知道内部有两个函数。调用者代码能够捕获所有拒绝,但它不打印解析的值。

代码中有什么错误?

代码语言:javascript
复制
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时正确拒绝。

EN

回答 1

Stack Overflow用户

发布于 2018-02-08 10:03:08

这个问题是由getsecondfn引起的,因为你没有在其中返回一个Promise (这意味着caller函数上的then块不会触发)。

参考下面的固定demo:

代码语言:javascript
复制
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);

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48676208

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档