async/await and recursion
async/await and recursion
我正在尝试编写一个方法,该方法递归地显示ActionSheetIOS,以从数组中选择包含的值并返回所选值:
async function _rescursiveSelect(data, index) {
if (index < data.length) {
const object = data[index];
if (object.array.length === 1) {
return await _rescursiveSelect(data, index + 1);
}
ActionSheetIOS.showActionSheetWithOptions({
title: 'Choose a value from array: ',
options: object.array,
},
buttonIndex => async function() {
const selectedValue = data[index].array[buttonIndex];
data[index].value = selectedValue;
delete data[index].array;
return await _rescursiveSelect(data, index + 1);
});
} else {
return data;
}
}
不幸的是,当我调用此方法时,它返回undefined
。我想这个问题来自于async/await的使用,但我还没有发现。
有什么建议吗?
它返回undefined
,因为有一条路径没有return
语句。async-await
模式可以很好地与异步函数配合使用,但是ActionSheetIOS.showActionSheetWithOptions
不是异步的。
异步函数只是一个返回Promise
的函数。async
关键字只是使异步代码可读的语法糖,并隐藏了其背后的promise处理
幸运的是,使用老式回调函数的库可以很容易地包装成新型Promise返回异步函数,如下所示:
function showActionSheetWithOptionsAsync(options) {
return new Promise(resolve => {
// resolve is a function, it can be supplied as callback parameter
ActionSheetIOS.showActionSheetWithOptions(options, resolve);
});
}
async function _rescursiveSelect(data, index) {
if (index < data.length) {
const object = data[index];
if (object.array.length === 1) {
return await _rescursiveSelect(data, index + 1);
}
const buttonIndex = await showActionSheetWithOptionsAsync({
title: 'Choose a value from array: ',
options: object.array
});
const selectedValue = data[index].array[buttonIndex];
data[index].value = selectedValue;
delete data[index].array;
return await _rescursiveSelect(data, index + 1);
} else {
return data;
}
}
相关文章:
- Selenium WebDriver and JavaScript change
- Javascript Recursion?
- PHP and Javascript functions
- Javascript Return and if/else
- SetTimeout and clearTimeout in Javascript
- lightbox in html 5 and javascript
- TimelineJS and AngularJS
- timeago.js with datatable and PHP
- javascript button ajax and php
- Ajax and Json with Rails
- Combine onload, onresize and onclick
- php布尔值's小写AND大写和数字布尔值'可以接受
- setTimeout and V8
- Jquery post and onclick
- Moment js and IOS
- Rails 3.2 and Paloma gem
- Backbone, TypeScript, and super
- Javascript, Node, Promises, and recursion
- async/await and recursion
- Javascript getters and setters - recursion issue