【问题标题】:How to return the result of a nested promise?如何返回嵌套承诺的结果?
【发布时间】:2016-02-19 06:41:47
【问题描述】:

我有两个功能。一个从数据库中获取用户,另一个循环遍历它们并将它们显示为列表:

store.findUsers = () => {
  function map (doc, emit) {
    if (doc.type === 'user') {
      emit(doc.createdAt)
    }
  }
  return db.query(map, {include_docs: true}).then(posts =>
    _.map(posts.rows, (post) => post.doc)
  )
}

store.getUserList = () => {
  store.findUsers().then(posts => {
    return _.map(posts, (post) => post)
  }).then(result => {
    return result
  })
}

我正在使用这样的功能:

var userList = store.getUserList()
console.log('User list:', userList)

但是,console.log('User list:', userList) 不输出任何内容。我认为这是因为store.getUserList() 中的return result 在嵌套的promise 中。

如何修改代码返回result

【问题讨论】:

    标签: javascript promise ecmascript-6


    【解决方案1】:

    不要退货;这不是 promises 的工作方式,并且几乎会破坏它们的目的。修改你的函数,让它返回一个承诺:

    store.getUserList = () => {
      return store.findUsers().then(posts => {
        return _.map(posts, (post) => post)
      }).then(result => {
        return result
      })
    }
    

    然后在调用函数时使用该承诺:

    store.getUserList().then( userList => {
        console.log('User list:', userList);
    } );
    

    您还可以简化store.getUserList at lot。 .then(result => { return result } ) 不执行任何操作,因此您可以将其删除,实际上您的地图正在传递标识函数,因此它也不执行任何操作。整个函数定义等同于store.getUserList = () => store.findUsers();,当您可以直接调用store.findUsers(); 并像这样使用它时,这似乎是一个非常无用的函数:

    store.findUsers().then( userList => {
        console.log('User list:', userList);
    } );
    

    【讨论】:

      【解决方案2】:

      所以,这里的关键是不返回任何东西。你不知道承诺什么时候会回来,所以返回并不意味着什么,因为代码不会等待你的承诺。

      在 Promise 的回调中调用另一个函数而不是返回,来做任何你想做的事情:

      doSomething.then((myData) => {
        somethingToDoWithData(myData);
      });
      

      【讨论】:

        猜你喜欢
        • 2014-07-05
        • 1970-01-01
        • 2019-02-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-24
        相关资源
        最近更新 更多