gpt4 book ai didi

javascript - 异步/等待和递归

转载 作者:数据小太阳 更新时间:2023-10-29 04:29:50 24 4
gpt4 key购买 nike

我正在尝试编写一种递归显示 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;
}
}

关于javascript - 异步/等待和递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33805176/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com