简体   繁体   English

LocalForage async/await getItem() 等待 2 个变量然后完成加载

[英]LocalForage async/await getItem() wait for 2 variables and then finish loading

I'm new to the Javascript async calls and understanding promises.我是 Javascript 异步调用和理解承诺的新手。 I'm so used to Do This, Wait for This.我已经习惯了这样做,等待这个。

I am using localforage in my site, and I need to get data from 2 sources.我在我的站点中使用 localforage,我需要从 2 个来源获取数据。

var ordersRaw = null
var itemsRaw = null
localforage.getItem('ordersRaw').then((res) => {
    if(res) {
        ordersRaw = res
    } 
})
localforage.getItem('itemsRaw').then((res) => {
    if(res) {
        itemsRaw = res
    } 
})
if(ordersRaw && itemsRaw) {
    // now load the screen
} else { console.log('NO DATA') }

After I have these 2 pieces of data, finish loading the screen by running a function在我有了这两条数据之后,通过运行一个函数来完成加载屏幕

displayWithResults()

But if I run it like this, it will instantly fail, because of the async functionality.但是如果我这样运行它,它会立即失败,因为异步功能。 and cause NO DATA to show up.并导致 NO DATA 出现。

I consistently run into this issue with javascript and I can't seem to fully wrap my head around it accurately.我一直在使用 javascript 时遇到这个问题,但我似乎无法准确地完全理解它。 Any help here is appreciated.在这里的任何帮助表示赞赏。

There are a few ways to solve this:有几种方法可以解决这个问题:

  • Nest the callbacks嵌套回调
  • Use async await using promises使用承诺使用异步等待
  • Store the results under a single key as nested properties in an object将结果存储在单个键下作为对象中的嵌套属性
  • Use Promise.all使用 Promise.all

It comes down to the fact that you want to retrieve all results asynchronously before performing the check.归结为您希望在执行检查之前异步检索所有结果。

I suggest that you use async await, it's just clean.我建议你使用 async await,它很干净。

The code would look something like this:代码看起来像这样:

(async() => {
    try {
        const ordersRaw = await localforage.getItem('ordersRaw');
        const itemsRaw = await localforage.getItem('itemsRaw');
        if(ordersRaw && itemsRaw) {
            // now load the screen
        } else { 
           console.log('NO DATA') }
        }
    } catch (e) {
        console.log(e);
    }
})();

Edit: Above code executes sequentially.编辑:以上代码按顺序执行。 Please replace with something like:请替换为类似以下内容:

const getOrders = localforage.getItem('ordersRaw');
const getItems = localforage.getItem('itemsRaw');
const [ordersRaw, itemsRaw] = await Promise.all([getorders, getItems]);

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

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