【问题标题】:How to use result of a function that uses promises如何使用使用承诺的函数的结果
【发布时间】:2017-04-30 09:45:09
【问题描述】:

我有一个函数,

  asdf() {
    var a = fooController.getOrCreateFooByBar(param);
    console.log("tryna do thing");
    console.log(a); //undefined
    if (!a.property) {
      //blah
    }

死了。 getOrCreateFooByBar 做了一个

  Model.find({phoneNumber : number}).exec()
  .then(function(users) {})

并找到或创建模型,并在最后返回:

.then(function(foo) { return foo}

如何在asdf() 中使用这个结果?我觉得这是一个相当简单的问题,但我被卡住了。如果我尝试执行 a.exec() 或 a.then() 我会收到“a cannot read property of undefined”错误。

【问题讨论】:

    标签: node.js mongoose promise es6-promise


    【解决方案1】:

    关于 Promise(与传递的回调相反)的主要思想是它们是您可以传递和返回的实际对象。

    fooController.getOrCreateFooByBar 需要返回从Model.find() 获得的 Promise(在完成所有处理之后)。然后,您就可以在asdf 函数中的a 中访问它。

    反过来,asdf() 应该返回一个 Promise,这将使 asdf() 也可以。只要你不断从异步函数返回 Promise,你就可以继续链接它们。

    // mock, you should use the real one
    const Model = { find() { return Promise.resolve('foo'); } }; 
    
    function badExample() {
      Model.find().then(value => doStuff(value));
    }
    
    function goodExample() {
      return Model.find().then(value => doStuff(value));
    }
    
    function asdf() {
      var a = badExample();
      var b = goodExample();
    
      // a.then(whatever); // error, a is undefined because badExample doesn't return anything
    
      return b.then(whatever); // works, and asdf can be chained because it returns a promise!
    }
    
    asdf().then(valueAfterWhatever => doStuff(valueAfterWhatever));

    【讨论】:

    • 啊,这是有道理的。我没有做return Model.find({... 谢谢!
    猜你喜欢
    • 2017-05-16
    • 2017-06-25
    • 2021-01-15
    • 2020-12-28
    • 2015-12-22
    • 1970-01-01
    • 2015-04-13
    • 2017-03-16
    • 1970-01-01
    相关资源
    最近更新 更多