简体   繁体   中英

Calling a function within a callback function of a callback function in Javascript

I'm quite new to javascript coding so I'm trying to wrap my head around callback functions. I think I'm close but keep hitting a roadblock.

I'm using jquery to post to a REST api and I need to call one function and then another and another in sequence. From looking up answers I've found I need to use callback functions.

I'm using the below script in my function but it keeps stopping at the first callback so I know I'm missing something but after testing loads I just can't figure out what. Could anyone help shed some light as to where I'm going wrong please?

Edited code based on feedback

this.placeNewOrder = function(){
  if(items.length ==0){
    alert("it was 0");
    this.addToOrder();
    newOrder(username, password, Id,function(){postOrder(username, password, Id, currentId);});
  }
}

this.newOrder = function(username, password, Id, callback){
  //some code
  var username = username;
  var password = password;
  var Id = resultOfSomeCalculation;

  callback(username,password,result,this.currentId);
  alert("callback2 called");
};

this.postOrder = function(username, password, Id, currentId){
  //some code
  alert("finished");
};

JavaScript promises were introduced for this use case.

A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.

A Promise is in one of these states:

  • pending: initial state, not fulfilled or rejected.
  • fulfilled: meaning that the operation completed successfully.
  • rejected: meaning that the operation failed.

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