我们有2个功能:
class AndroidGameFragment () : AndroidFragmentApplication(){
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
super.onCreateView(inflater, container, savedInstanceState)
val config = AndroidApplicationConfiguration()
return initializeForView(MyGdxGame(), config)
}
}
在我的函数正文中,您可以看到我正在调用submitEstateObject = () => {
// if (!this.state.formIsValid) {
// this.setState({ showFieldErrors: true })
// console.log(this.state)
// } else {
//this.setState({ isLoading: true })
console.log('Category', this.state.estateForm.category.value)
console.log('Type', this.state.estateForm.type.value)
console.log('Params', this.state.estateParams)
console.log('ContactsAndOwners', this.state.contactsAndOwners)
console.log('Photos', this.state.photos)
//Submit photos
const test = this.uploadPhotos() // WAIT UNTILL FUNC RETURN ARRAY!
//AFTER TEST WAS DONE RUN CODE BELOW
console.log('Test', test)
console.log('Test2')
//}
}
。此func必须返回对象数组,然后我要继续执行下面的另一个代码。该怎么做?
uploadPhotos
答案 0 :(得分:2)
您要使用Promise.all(promiseArray)
代替console.log(photosToSave)
尝试
Promise.all(photosToSave).then(arr => console.log(arr))
.catch(err => console.log('Something failed', err)
答案 1 :(得分:1)
有两种方式处理承诺。通过回调(解决)或实际返回承诺。我要解决后者。
每次您在承诺中退还某些东西时,都会将其作为承诺退还。因此,您需要在promise中包装对返回promise的函数的调用。
示例:
function ajaxCall(url) {
return return AJAXRequest(url);
}
function getSearch() {
ajaxCall('http://test.com') // Calling a function that returns an ajax call.
.then(function (ajaxResponse) {
// code that handles ajaxRespons
});
}
但是在您的uploadPhotos
方法中,什么也不返回。您需要返回Promise.all。
// the equivalent to my ajaxCall example
uploadPhotos = () => {
// other code
return Promise.all(photosToSave) // added 'return' and removed the return statement inside the Promise.all method.
}
然后应将响应作为承诺处理。
// the same as in my getSearch example
const test = this.uploadPhotos()
.then(function (ajaxResponse) {
//AFTER TEST WAS DONE RUN CODE BELOW
console.log('Test', ajaxResponse)
});
更多阅读内容:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise