2017-10-11 75 views
0

我必须在measure()函数的帮助下测量几个值。
因为是异步操作,我只能写:同时调用多个“测量”操作

this.refContainerView.measure((x, y, width, height, pageX, pageY) => { 
    const containerViewHeight = height 

    this.refCommentList.measure((x, y, width, height, pageX, pageY) => { 
    const commentListOffset = pageY 
    const commentListHeight = height 

    // do something 

    }) 
}) 

,如果需要测量更多的组件,它看起来像一个回调地狱。
是否可以同步编写代码,例如在await或其他帮助下,例如:

const contaierView = this.refContainerView.measure() 
const commentList = this.refCommentList.measure() 

// and then do something with 
contaierView {x, y, width, height, pageX, pageY} 
commentList {x, y, width, height, pageX, pageY} 

回答

0

我找到了这种解决方案。
measure()不是承诺,但具有回拨功能:

measureComponent = component => { 
    return new Promise((resolve, reject) => { 
    component.measure((x, y, width, height, pageX, pageY) => { 
     resolve({ x, y, width, height, pageX, pageY }) 
    }) 
    }) 
} 

onDoSomething = async() => { 
    const [containerView, commentList] = await Promise.all([ 
    this.measureComponent(this.refContainerView), 
    this.measureComponent(this.refCommentList), 
    ]) 

    // do here with containerView and commentList measures 
    } 
}