【发布时间】:2018-04-14 09:29:32
【问题描述】:
考虑这段代码
const response = await fetch('<my url>');
const responseJson = await response.json();
responseJson = _.sortBy(responseJson, "number");
responseJson[0] = await addEnabledProperty(responseJson[0]);
addEnabledProperty 所做的是扩展对象,添加一个enabled 属性,但这并不重要。函数本身运行良好
async function addEnabledProperty (channel){
const channelId = channel.id;
const stored_status = await AsyncStorage.getItem(`ChannelIsEnabled:${channelId}`);
let boolean_status = false;
if (stored_status == null) {
boolean_status = true;
} else {
boolean_status = (stored_status == 'true');
}
return _.extend({}, channel, { enabled: boolean_status });
}
有没有办法使用_.map(或其他系统)循环整个responseJson数组以对每个元素使用addEnabledProperty?
我试过了:
responseJson = _.map(responseJson, function(channel) {
return addEnabledProperty(channell);
});
但它没有使用异步,所以它冻结了应用程序。
我试过了:
responseJson = _.map(responseJson, function(channel) {
return await addEnabledProperty(chanell);
});
但是我遇到了一个 js 错误(关于行 return await addEnabledProperty(chanell);)
await 是保留字
然后尝试
responseJson = _.map(responseJson, async function(channel) {
return await addEnabledProperty(channell);
});
但是我得到了一系列 Promise...我不明白为什么...
还有什么!??
编辑:我了解您对我没有指定 addEnabledProperty() 返回 Promise 的抱怨,但是,真的,我不知道。事实上,我写了“我得到了一个 Promise 数组......我不明白为什么”
【问题讨论】:
-
“但是我得到了一个 Promise 数组……我不明白为什么……” 因为
async函数返回一个 Promise 并且.map创建回调返回的值的数组。Promise.all是“解决”一系列承诺的方式。 -
根据您的第三个示例,任何
async函数总是返回一个promise,这就是您获得它们数组的原因。但是,你可以试试:responseJson = await Promise.all(_.map(responseJson, function(channel) { return addEnabledProperty(channel) })) -
await is a reserved word你从哪里得到这个错误的? -
addEnabledProperty是否返回Promise? -
@guest271314 我希望如此,因为 OP 在他的第一个 sn-p 中是
awaiting 它。编辑:我应该注意,等待非承诺仍然有效,所以也许它不是?。
标签: javascript async-await lodash