Ionic 3 在继续下一个功能之前完成一个功能

Ionic 3 finish one function before proceeding to next function

在我下面的代码中,我想完成

  this.storage.set ("location", JSON.stringify(lsd_info)); 

在继续

之前
this.driveTo();

我相信我应该使用 .then()。我想知道是否有一个简单的解决方案可以在继续之前完成一个事件。

getLoc() {
    let a = this.data.lsd;
    let b = this.data.sec;
    let c = this.data.twp;
    let d = this.data.rng;
    let e = this.data.mrd;

    this.http.get('https://www.reversegeocoder.com/api/v1/PrivateID/lsd/' + a + '-' +  b  + '-' + c + '-' +  d  + ' ' + e)
    .map(res => res.json())
    .subscribe (data => {
        let lsd_info = {
            latitude: data[0].response.lat,
            longitude: data[0].response.lng,
        };

        let lsd_error = {error: data[0].response.err};
        this.ErrorResponse = (JSON.stringify(data[0].response.err));
        this.ErrorText = this.ErrorResponse.replace('[','').replace(']','');
        this.storage.set ("location", JSON.stringify(lsd_info));

        //finish storage.set before proceeding

        this.driveTo();

        },
            err => {
                console.log('error');
            }
    );
}

driveTo() {
    this.navCtrl.push(Drive);
}

或者有两个函数,其中一个函数在继续之前完成

即getLoc() 然后 driveTo()

你猜对了。一旦离子storage设置了键值对,你应该使用.then()来放置你的代码应该运行,作为ionic storage returns一个承诺解决,当键值已设置。我已经修改了你的代码,解决方案很简单。

getLoc() {
let a = this.data.lsd;
let b = this.data.sec;
let c = this.data.twp;
let d = this.data.rng;
let e = this.data.mrd;

this.http.get('https://www.reversegeocoder.com/api/v1/PrivateID/lsd/' + a + 
'-' +  b  + '-' + c + '-' +  d  + ' ' + e)
.map(res => res.json())
.subscribe (data => {
    let lsd_info = {
        latitude: data[0].response.lat,
        longitude: data[0].response.lng,
    };

    let lsd_error = {error: data[0].response.err};
    this.ErrorResponse = (JSON.stringify(data[0].response.err));
    this.ErrorText = this.ErrorResponse.replace('[','').replace(']','');
    this.storage.set ("location", JSON.stringify(lsd_info)).then(
    (value) => {
       // storage.set finished
       this.driveTo();
    },
    (reason) => {
       console.log('Error occurred.');
       console.warn(reason);
    });

    },
        err => {
            console.log('error');
        }
    );
}

driveTo() {
  this.navCtrl.push(Drive);
}