2017-10-11 76 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 
    } 
}