【问题标题】:async/await and recursion异步/等待和递归
【发布时间】:2016-02-21 16:06:45
【问题描述】:

我正在尝试编写一种方法,该方法以递归方式显示 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 using 但我还没有找到它。

有什么建议吗?

【问题讨论】:

    标签: javascript react-native ecmascript-2017


    【解决方案1】:

    它返回undefined,因为有一条路径没有return 语句。 async-await 模式适用于异步函数,但 ActionSheetIOS.showActionSheetWithOptions 不是异步的。

    异步函数只是一个返回Promise 的函数。 async 关键字只是使异步代码可读的语法糖,并隐藏了它背后的 Promise 处理。

    幸运的是,使用旧式回调函数的库可以很容易地包装成新式 Promise-returning async 函数,如下所示:

    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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-08-28
      • 1970-01-01
      • 2021-05-12
      • 2015-08-27
      • 2014-01-24
      • 2020-09-08
      • 1970-01-01
      • 2019-04-22
      • 2018-07-24
      相关资源
      最近更新 更多