How to run the method only after the previous function has ended

Asked

Viewed 655 times

0

I have the code below, but the method showVideo() is executed and follows the execution at the same time of the code below it, without waiting for the showVideo() is due to simultaneous execution the value set in the Storage is not correct.

buscaBonus() {

     this.servicoGeral.showVideo(); //esse metodo chama o `addTempo()` que por 
     sua vez chama um localStorage.setItem para setar o tempo ganho, e o código 
     abaixo recupera esse valor para mostrar em tela. Só deveria executar o 
     código abaixo após o `showVideo()`.

     if (localStorage.getItem("segundos") == undefined) {
       this.totalBonus = localStorage.getItem("segundos");
     }    

     let alert = this.alertCtrl.create({
      title: 'Você ganhou 5 segundos de bônus!',
      message: 'Poderá utilizar e até acumular para jogar qualquer fase.',
      buttons: [
        {
          text: 'Entendi ',
          handler: () => {
            return true;
          }
        }
      ],
      enableBackdropDismiss: false
      });    
      alert.present();      
    }

     showvideo(): Promise<boolean>{    
        const rewardVideoConfig: AdMobFreeRewardVideoConfig = {
          id: 'ca-app-pub-1390341047819209/6782590495',
          isTesting: true,
          autoShow: true
        }

        this.admobFree.rewardVideo.config(rewardVideoConfig);
        return new Promise<boolean>((resolve) => {

          rewardVideoClose = this.admobFree.on(this.admobFree.events.REWARD_VIDEO_CLOSE).subscribe(() => {

          });
          rewardVideoReward = this.admobFree.on(this.admobFree.events.REWARD_VIDEO_REWARD).subscribe(() => {
            this.addTempo();
            rewardVideoReward.unsubscribe();
          });

          this.admobFree.rewardVideo.prepare()
            .then(() => { })
            .catch(() => {
              loading.dismiss();
              resolve(false);
            });
        }); 
     } 
      addTempo() {
         if (localStorage.getItem("segundos") == null) {
           this.tempoSegundos = 5
         } else {
           let tempo = localStorage.getItem("segundos");
           this.tempoSegundos = (parseInt(tempo) + 5)
         }
         let tempo: string;
         tempo = this.tempoSegundos.toString()
         localStorage.setItem('segundos', tempo);
     }

2 answers

1

What would be the first function you perform?

Try to call the this.addTempo()as in this example, using a callback.

funcao() {
  let loader = this._loaderCtrl.create();
  loader
    .present()
        .then(() => {
           .subscribe(
              () => {
              let toast = this._toastCtrl.create({
                message: "mensagem",
                duration: 3000
              });
              toast.onDidDismiss(() => {
                this.addTempo()
              });
          toast.present();
        loader.dismiss();
 }

Example with loading:

loader.dismiss(()=>{
    this.addTempo()
 });
  • Should this function be observable? I am trying to use your code to do a test and error occurs in subscribe.

  • Trying to use without the same subscribe, was just an example.

  • I think my problem is before then, because I have a method that calls this showVideo: searchBonus() hein this.servicoGeral.showVideo() //AT THIS TIME BEFORE THE ABOVE FUNCTION ALREADY EXECUTES THE BELOW CODE this.totalBonus = localStorage.getItem("seconds"); //AND CONSEQUENTLY STILL DOES NOT HAVE VALUE SAVED IN STORAGE }

  • I wanted to format the code above, but I couldn’t

  • Can you edit and put in the post? maybe you’ll get better understand

  • done, I think I’ve changed up the problem now, I’ve remade the whole question.

  • this.admobFree.rewardVideo.prepare()&#xA; .then(() => {this.addTempo })&#xA; .catch(() => {&#xA; loading.dismiss();&#xA; resolve(false);&#xA; });

  • doesn’t work buddy

  • calling on prepare the video has not been watched yet and should not go through the addTempo(), the right would be at this event REWARD_VIDEO_REWARD, but I’ve made it with promisse and the functions are executed one after the other not waiting for the end of the first. I’ve tried several ways.

Show 4 more comments

-1

You can create a barrier, same method used in asynchronous requests, at a glance, maybe I can help you.

var simpleBarrier = require('simple-barrier'),
fs = require('fs');

// create a barrier instance
var barrier = simpleBarrier();

// load some files, let the barrier handle the callbacks:
fs.readFile('foo.txt', barrier.waitOn());
fs.readFile('bar.txt', barrier.waitOn());
fs.readFile('baz.txt', barrier.waitOn());

// add a callback for when all files are loaded
barrier.endWith(function( results ){

   // Results is an array of the values given by fs.readFile
   // the array is in the order that barrier.waitOn() was called, regardless of the 
   // order they were loaded in
   console.log('foo, bar, and baz are:', results.join('\n'));
});

Source: https://github.com/jimhigson/simple-barrier

  • 1

    The ideal is to bring the important information from the links to the answers considering that they can be changed/deleted at the source, which will end up leaving a vacuum in your response. Of course the link remains a reference.

  • I appreciate the help friend, but I haven’t been able to solve my problem, unfortunately, I did several forms for bars processing and still nothing helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.