rea*_*ebo 14 javascript async-await lodash
考虑这段代码
const response = await fetch('<my url>');
const responseJson = await response.json();
responseJson = _.sortBy(responseJson, "number");
responseJson[0] = await addEnabledProperty(responseJson[0]);
Run Code Online (Sandbox Code Playgroud)
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 });
}
Run Code Online (Sandbox Code Playgroud)
有没有办法使用_.map(或另一个系统)循环通过整个responseJson数组来addEnabledProperty对每个元素使用?
我试过了:
responseJson = _.map(responseJson, function(channel) {
return addEnabledProperty(channell);
});
Run Code Online (Sandbox Code Playgroud)
但它没有使用异步,所以它冻结了应用程序.
我试过了:
responseJson = _.map(responseJson, function(channel) {
return await addEnabledProperty(chanell);
});
Run Code Online (Sandbox Code Playgroud)
但我得到一个js错误(关于行return await addEnabledProperty(chanell);)
等待是一个保留字
然后试过
responseJson = _.map(responseJson, async function(channel) {
return await addEnabledProperty(channell);
});
Run Code Online (Sandbox Code Playgroud)
但我得到了一系列的承诺......我不明白为什么......
还有什么!??
编辑:我理解你的抱怨我没有指定addEnabledProperty()返回a Promise,但是,真的,我不知道.事实上,我写道" 我得到了一系列的承诺......我不明白为什么 "
dhi*_*ilt 33
要并行处理您的响应jsons,您可以使用Promise.all:
const responseJson = await response.json();
responseJson = _.sortBy(responseJson, "number");
let result = await Promise.all(_.map(responseJson, async (json) =>
await addEnabledProperty(json))
);
Run Code Online (Sandbox Code Playgroud)
由于addEnabledProperty方法是异步的,因此以下也应该有效(每个@CRice):
let result = await Promise.all(_.map(responseJson, addEnabledProperty));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11321 次 |
| 最近记录: |