简体   繁体   中英

promise not returning value in order

Hello I am new to ionic,

I want to fetch data from pouch-db in background.
After doing a bit research I found, concept of promise will solve my problem.

I want to execute my console logs in order given below 1, 2 and 3

Here is my code:

Class:

class1{

 method1(){
    class2Provider.method2().then(function (result:any) {

      console.log("3")
      console.log("VSCP "+result);
      this.navCtrl.push('InspectionPage',{'inspectnData':result});

   })
 }

}

Provider1:

export class ModelProvider {

 method2(){
  return new Promise (resolve => {

            this.dbHelpr.getRecord().then(function (result:any) {
                console.log("2")
                console.log("data for inspectId is -------------"+JSON.stringify(tempData));
                resolve(result)
            })
        })
 }

}

Provider2:

export class DbHelperProvider {

  getRecord(){

        return new Promise(resolve => {
          this.db.get(_id).then(function (doc) {
            console.log("1")
            resolve(doc);
          }).catch(function (err) {
            console.log(err);
            resolve("fail");
          });
        })


      }
   }

Above code executes log 3 first and shows error with

Cannot read property 'navCtrl' of undefined

How do I execute functions in order I want?

Use Fat arrow function => instead of function .

class1{

    method1(){
        class2Provider.method2().then((result: any) => {
            console.log("3")
            console.log("VSCP " + result);
            this.navCtrl.push('InspectionPage', { 'inspectnData': result });
        })
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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