The worm
The worm

Reputation: 5888

How to start off a promise in JavaScript?

This may seem like a weird question but allow me to explain: I have this function that I want to turn into a promise because I believe some events are not firing fully and others are starting before (e.g. the state of playersOverallTotal is wrong because I don't think it has taking into account the code above so I need to wait for it to finish before setting state

  handleClickTwist() {
    this.dealToPlayer();
    this.forceUpdate();
    let playersDeck = this.state.playersDeck;
    let playersDeckTotal = [];
    for (var i=0; i < playersDeck.length; i++){
      playersDeckTotal.push(playersDeck[i].rankValue)
    }

    let total = playersDeckTotal.reduce(function(a, b) {
        return a + b;
      },
    0);

    this.setState({playersOverallTotal: total});
    this.total();
  };

I know promises look something like the below

  anotherFunc(){
    return new Promise((resolve, reject) => {
      resolve()
    }
  }

and then I can call something like this:

this.func().then(() => {
      return this.anotherFunc();
    }).then(() => {
      return Promise.resolve(this.setState({playersOverallTotal: total}))
    }).then(() => {
      return this.anotherFun();

but I cant think how to do it for this code so far. or rather, what is the initial function I can call in the anotherFunc() to kick the function off?

Upvotes: 3

Views: 3865

Answers (1)

Alexander_F
Alexander_F

Reputation: 2877

Maybe you are missing some common understanding:

First, I don't see any possible Problems with your code, that could be solved by promises, but any way, as in your example:

anotherFunc(){
    return new Promise((resolve, reject) => {

      // do some crazy stuff here
      // if you do an ajax call put "resolve" 
      // into success function after ajax is finished

      if(allIsFine) {
        resolve(passAnyData);
      } else { reject() };
    }
  }

then a call

anotherFunc().then(function(passAnyData) {
// resolve called with passAnyData


}).catch(function() {
// some error
});

Upvotes: 4

Related Questions