有没有办法等到功能完成? [英] Is there a way to wait until a function is finished?

查看:104
本文介绍了有没有办法等到功能完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从函数中的AsyncStorage获取信息(真/假),并创建一个字符串,该字符串对于下一步获取数据很重要.我的问题是,直到需要字符串后,函数才能完成.

I'm trying to get information (true/false) from AsyncStorage in a function and create a string which is importent to fetch data in the next step. My problem is, the function is not finished until the string is required.

我尝试了许多来自Internet的解决方案,例如异步函数,然后等待getItem或.done()或.then(),但没有一个对我有用.

I tried many solutions from the internet like async function and await getItem or .done() or .then(), but none worked out for me.

当前行为是,控制台显示的是"channel required channel:"而不是"channel:channel_id0".

The current behaviour is that the console displays first "channel required: " than "channel: channel_id0".

推荐答案

问题的不清楚之处:

  1. 您无需说明设置了this.state.firstValue的时间以及它与您要实现的目标之间的关系.

  1. You don't say when this.state.firstValue is set, and how that relates to what you are trying to accomplish.

您有一个for-loop,可以在其中多次设置相同的值.

You have a for-loop where you could be setting the same value multiple times.

变异状态,而不是设置状态.这不好,请参见此 SO问题

You mutate the state rather than set it. This is not good, see this SO question for more on that.

我们可以做一些事情来使您的代码更容易理解.下面,我将显示一个可能的重构.解释我在每个步骤中所做的事情.我正在使用async/await,因为它会导致更整洁和更易于阅读的代码,而不是使用promises,在回调中您可能会迷路.

There are somethings we can do to make your code easier to understand. Below I will show a possible refactor. Explaining what I am doing at each step. I am using async/await because it can lead to much tidier and easier to read code, rather than using promises where you can get lost in callbacks.

  1. 从AsyncStorage获取所有密钥
  2. 确保所有键都有一个值.
  3. 过滤键,以便我们仅包括不包含字符串'not'的键.
  4. 使用Promise.all,这一部分很重要,因为它基本上获取了我们刚刚找到的每个键的所有值,并将它们放入名为items
  5. 的数组中
  6. items数组中的每个对象都有一个keyvalue属性.
  7. 然后我们过滤items,以便仅保留带有item.value === 'true'的内容.
  8. 然后我们过滤items,以便仅保留带有item.value !== 'true'的那些. (这可能是可选的,它实际上取决于您要执行的操作)
  9. 我们还能返回什么?您需要添加该部分.
  1. Get all the keys from AsyncStorage
  2. Make sure that there is a value for all the keys.
  3. Filter the keys so that we only include the ones that do not contain the string 'not'.
  4. Use a Promise.all, this part is important as it basically gets all the values for each of the keys that we just found and puts them into an array called items
  5. Each object in the items array has a key and a value property.
  6. We then filter the items so that only the ones with a item.value === 'true' remain.
  7. We then filter the items so that only the ones with a item.value !== 'true' remain. (this may be optional it is really dependent on what you want to do)
  8. What do we return? You need to add that part.

这里是重构:

_getFetchData = async () => {
  let allKeys = await AsyncStorage.getAllKeys();                             // 1
  if (allKeys.length) {                                                      // 2

    let filteredKeys = allKeys.filter(key => !key.includes('not'));          // 3
    let items = await Promise.all(filteredKeys.map(async key => {            // 4
      let value = await AsyncStorage.getItem(key);
      return { key, value };                                                 // 5
    }))

    let filteredTrueItems = items.filter(item => items.value === 'true');    // 6
    let filteredFalseItems = items.filter(item => items.value !== 'true');   // 7
    // now you have two arrays one with the items that have the true values 
    // and one with the items that have the false values
    // at this points you can decide what to return as it is not 
    // that clear from your question

    // return the value that your want                                       // 8
  } else {
    // return your default value if there are no keys                        // 8
  }
}

您将按以下方式调用此函数:

You would call this function as follows:

_fetchData = async () => {
  let channel = await this._getFetchData();
  console.log("channel required: " + channel);
}

尽管上面的方法可以工作,但是由于您不清楚要返回哪个值,因此当前不会返回任何值.我建议您以我在此处编写的代码为基础,并对其进行更新,以使其返回所需的值.

Although the above will work, it will not currently return a value as you haven't made it clear which value you wish to return. I would suggest you build upon the code that I have written here and update it so that it returns the values that you want.

为进一步阅读,我建议迈克尔·陈(Michael Chan)撰写的这些很棒的文章,讨论state

For further reading I would suggest these awesome articles by Michael Chan that discuss state

https://medium.learnreact.com/setstate-is-asynchronous-52ead919a3f0

https://medium.learnreact.com/setstate-takes-a -callback-1f71ad5d2296

https://medium.learnreact.com/setstate-takes-a -function-56eb940f84b6

我还建议您花一些时间来阅读有关async/awaitpromises

I would also suggest taking some time to read up about async/await and promises

https://medium.com/@bluepnume/learn-about-promises-before-you-start-using-async-await-eb148164a9c8

最后,这篇文章和关于Promise.all的问题都很好

And finally this article and SO question on Promise.all are quite good

https://www.taniarascia.com/promise-all- with-async-await/

将async/await与forEach循环配合使用

这篇关于有没有办法等到功能完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆