简体   繁体   English

等待异步完成(等待)

[英]Wait until async is completed (await)

I am trying to get my head around with async/await 我正在尝试异步/等待

I am using https://github.com/sunnylqm/react-native-storage for my project in react-native. 我在React-native中为我的项目使用https://github.com/sunnylqm/react-native-storage

I am using async storage to store few critical information such as selected user locale, I need to retrieve this value before screen is rendered to display screen based on selected locale. 我正在使用异步存储来存储一些关键信息,例如选定的用户区域设置,因此我需要在渲染屏幕以基于选定的区域设置显示屏幕之前检索此值。

I have tried implementing several helper functions, it works with callback, what I need is to return the value instead of callback and wait until the value is fetched. 我已经尝试实现一些辅助函数,它可以与回调一起使用,我需要返回的是值而不是回调,然后等到获取值为止。 Below are few examples I tried. 以下是我尝试过的一些示例。

// 1
_selectedLocale = async () => {
  try {
    const value = await global.storage.load({key: 'selectedLocale'});
    return value
   } catch (error) {
     console.log(value)
   }
}
var selectedLocale = _selectedLocale();

// 2
export async function _selectedLocale() {
  return storage.load({key: 'selectedLocale'});
}
var selectedLocale = _selectedLocale();
// 3
export function selectedLocale(callback) {
  storage.load({key: 'selectedLocale'}).catch(e => {
    callback(RNLanguages.language);
  }).then(function(locale) {
    callback(locale);
  });
}

This is not working, I am looking to 这不起作用,我正在寻找

  1. Implement a helper function to retrieve a value based on key 实现一个辅助函数以根据键检索值
  2. Wait until the value is retrieved (sync) 等待直到检索到值(同步)

Can someone point me to right direction 有人可以指出我正确的方向吗

Thanks 谢谢

UPDATE1: UPDATE1:

Here is how I am using the callback 这是我使用回调的方式

selectedLocale(function(locale) {
  global.layoutIsRTL = 'ar' == locale;
  ReactNative.I18nManager.allowRTL(true);
  global.i18n.locale = locale
});

UPDATE2: UPDATE2:

It seems someone has already done this, here is the reference https://github.com/sunnylqm/react-native-storage/issues/206 unfortunately I am having hard time understanding it. 似乎已经有人这样做了,不幸的是,这里是参考https://github.com/sunnylqm/react-native-storage/issues/206,我很难理解。

async implicitly returns a promise, so you need to await the function call as well if you want the value there: async隐式地返回一个Promise,因此,如果要在该处调用值,则还需要等待函数调用:

var selectedLocale = await _selectedLocale();

but you can only do that inside of another async function 但您只能在另一个async函数中执行此操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM