async/await和recursion

Jea*_*ent 8 javascript react-native ecmascript-2017

我正在尝试编写一个方法来递归显示一个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;
  }
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,当我调用这个方法时,它会返回undefined.我想这个问题来自async/await使用,但我还没有计算它.

有什么建议吗?

Tam*_*dus 14

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

异步函数只是一个返回a的函数Promise.该async关键字只是一个语法糖,使异步代码的可读性,并隐藏了承诺处理它后面.

幸运的是,使用旧式回调函数的库可以很容易地包装到新式的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;
    }
}
Run Code Online (Sandbox Code Playgroud)