【问题标题】:Returning from function containing promise.all从包含 promise.all 的函数返回
【发布时间】:2018-12-05 20:07:20
【问题描述】:

我正在使用下面的异步代码来获取 url 数组,一旦所有 url 都被获取并添加到对象 mapGeometry 中。我需要从函数 returnMapGeometry 返回 mapGeometry,因此所有代码都需要暂停,直到我这样做。

我在正确使用语法时遇到了很多麻烦,如何在所有提取都已解决并且每个 mapGeometryPiece 都已添加到 mapGeometry 后返回 mapGeometry?

function returnMapGeometry() {
  var mapGeometry = new THREE.Group();

  Promise.all(
    urls.map((url, index) => fetch(new Request(url))
      .then(response => response.blob())
      .then(blob => doSomeWork(URL.createObjectURL(blob))
        .then(mapGeometryPiece => {
          mapGeometry.add(mapGeometryPiece)
        })
      ))
  }
  // code must pause until returnMapGeometry() returns

  mapGeometry = returnMapGeometry()

注意:mapGeometry 是 Three.js 组 - 我认为这没有任何区别,请参阅:https://threejs.org/docs/#api/objects/Group

【问题讨论】:

  • code must pause - 如果你想暂停,javascript 是错误的语言
  • Promise.all()返回承诺。调用者使用.then() 承诺获得结果。 Javascript 中没有暂停。必须学习异步编程。
  • 我的意思是,问题中的代码甚至不解析......所以,你怎么能指望它做任何事情!

标签: javascript es6-promise


【解决方案1】:

您需要在Promise.all 上链接并返回一个.then,该Promise.all 使用您构造的mapGeometry 进行解析,然后当您调用returnMapGeometry 时,它将使用mapGeometry 解析。因为它需要返回 Promise 而不是实际的 mapGeometry,所以调用函数稍微不同会更有意义,也许是 getMapGeometry

也可以去掉doSomeWork上不必要嵌套的.then,让代码更扁平:

function getMapGeometry() {
  var mapGeometry = new THREE.Group();

  return Promise.all(
    urls.map((url, index) => fetch(new Request(url))
      .then(response => response.blob())
      .then(blob => doSomeWork(URL.createObjectURL(blob))
      .then(mapGeometryPiece => mapGeometry.add(mapGeometryPiece))
    ))
  )
    .then(() => mapGeometry);
  // code must pause until returnMapGeometry() returns
}
getMapGeometry()
  .then((mapGeometry) => {
    // do stuff with mapGeometry
  });

【讨论】:

    猜你喜欢
    • 2019-02-04
    • 2018-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-25
    • 1970-01-01
    • 2019-05-06
    相关资源
    最近更新 更多