【问题标题】:How do I check whether a function which uses a promise was successful?如何检查使用 Promise 的函数是否成功?
【发布时间】:2019-01-09 14:47:33
【问题描述】:

我有这两个功能。当我调用 foo 时我想要什么,然后检查它是否成功。所以目前我正在按照这个答案中的建议做一些事情:Returning a value from a function depending on whether a Promise was resolved or not

function foo() {
  performOp()
    .then(() => {
      console.log('it worked!');
      return true;
    })
    .catch(err => {
      console.log('it failed!');
      return false;
    });
}

function bar() {
  foo().then(val => console.log(val));
}

这里的想法是 foo 会返回一个 promise 给 bar,bar 会打印结果。相反,我看到的是 foo() 的返回值是未定义的。

【问题讨论】:

  • 你不会在 foo 中返回任何东西。

标签: javascript node.js asynchronous promise


【解决方案1】:

我认为是因为您没有返回任何内容,否则该函数默认返回undefined。鉴于performOppromise,它将是:

function foo() {
  return performOp()
    .then(() => {
      console.log('it worked!');
      return true;
    })
    .catch(err => {
      console.log('it failed!');
      return false;
    });
}

【讨论】:

  • 谢谢。以这种方式使用 Promise 是否被认为是好的做法?
  • 这与好的做法或坏的做法无关。如果你想用它来链接承诺,你必须从函数中返回承诺。 return truereturn false 是特定 then/catch 回调的返回值。这种承诺链非常普遍。对于 ref,您可以查看 async/await,它主要是语法糖,但语法更简单。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-04
  • 1970-01-01
  • 1970-01-01
  • 2022-01-24
  • 1970-01-01
  • 1970-01-01
  • 2018-05-30
相关资源
最近更新 更多