Ionic2 存储 Promise.all 范围

Ionic2 Storage Promise.all scope

有人知道如何将 Ionic2 Storage.get 值分配给我的局部变量吗?如果我在 .then 中 console.log,工作正常,但它似乎只存在于 function/method 中。 我看到的大多数示例都展示了如何 'get' 我的数据,但没有真正将其应用于我的其他代码

-谢谢

import { Storage } from '@ionic/storage';

export class MyApp {

favDessertMax: string;
favDessertRuby: string;

constructor(storage: Storage) { }

 storage.ready().then(() => {

   this.storage.set('Max', 'Apple sauce');
   this.storage.set('Ruby', 'Banana split');


   Promise.all([
       this.storage.get('Max'),
       this.storage.get('Ruby'),
   ])
     .then(([val1,val2]) => {
       this.favDessertMax = val1; 
       this.favDessertRuby = val1;
       console.log(val1 + " " + val2); //values work here
     })
   console.log(val1 + " " + val2); // values don't work out here (or anywhere else)
   });

  storyTime() { // Need value to work here
    let myStory = 'Max likes ' + this.favDessertMax + ' and Ruby Likes 'this.favDessertRuby';
  return myStory;
  }

}

Promise.all 正在将数据设置到您的局部变量。它是异步的,因此当您调用 storyTime() 可能无法获取数据。 您将必须链接承诺以确保您将获得数据。

getData(){

    return Promise.all([
           this.storage.get('Max'),
           this.storage.get('Ruby'),
       ])
         .then(([val1,val2]) => {
           this.favDessertMax = val1;  // from 'Max'
           this.favDessertRuby = val2; // from 'Ruby'
           return [val1,val2];//return value in then.
           console.log(val1 + " " + val2); //values work here
         })
       });
    }

storyTime() { // Need value to work here
    return this.getData().then([val1,val2]=>{
    let myStory = 'Max likes ' + val1 + ' and Ruby Likes '+ val2 + ';
    return myStory;
     });
  }