async/await and recursion

async/await and recursion

本文关键字:recursion and await async      更新时间:2023-09-26

我正在尝试编写一个方法,该方法递归地显示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;
    }
}