离子存储GET

问题描述

我尝试从离子存储中获取价值,但这在这里行不通。为什么GET2在storage.get之前执行?我的大脑坏了,请帮忙。

  public storageGet(key: string){
    var uid = 0;
     this.storage.get(key).then((val) => {
      console.log('GET1: ' + key + ': ' + val);
      if (val != null) { uid = val;}
    });
    console.log('GET2: ' + key + ': ' + uid);
  return uid;
  }

返回:

GET2: uid: 0
GET1: uid: 1

解决方法

您需要了解诺言如何运作。

此代码是异步的,then回调中的所有行都将执行,但是您无法确定何时。

console.log("GET2")严格在storage.get之后执行,这部分是同步的。