繁体   English   中英

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

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

我是 Javascript 异步调用和理解承诺的新手。 我已经习惯了这样做,等待这个。

我在我的站点中使用 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') }

在我有了这两条数据之后,通过运行一个函数来完成加载屏幕

displayWithResults()

但是如果我这样运行它,它会立即失败,因为异步功能。 并导致 NO DATA 出现。

我一直在使用 javascript 时遇到这个问题,但我似乎无法准确地完全理解它。 在这里的任何帮助表示赞赏。

有几种方法可以解决这个问题:

  • 嵌套回调
  • 使用承诺使用异步等待
  • 将结果存储在单个键下作为对象中的嵌套属性
  • 使用 Promise.all

归结为您希望在执行检查之前异步检索所有结果。

我建议你使用 async await,它很干净。

代码看起来像这样:

(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);
    }
})();

编辑:以上代码按顺序执行。 请替换为类似以下内容:

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