I am using Promise to ensure one ajax completes before the next starts. I am having trouble passing an array variable to the second function. When I just have the variable "numExeDetails" it works. The issue occurs when I include the second variable "exercises", which is an array. I am receiving the error "TypeError: Cannot read properties of undefined (reading '0') Error in exerciseOverview.js - call 'loadExerciseDetails' function"
The code is:
//Display the exercise table
exerciseFirstColumnDetails()
.then((numExeDetails, exercises) => {
loadExerciseDetails(numExeDetails, exercises)
})
.catch((error) => {
console.log(error " Error in exerciseOverview.js - call 'loadExerciseDetails' function");//This is displayedWhen I just have the variable
})
function exerciseFirstColumnDetails() {
var numExeDetails = 0;
var exercises = [];
return new Promise((resolve, reject) => {
$.ajax({
//ajax stuff
})
.fail (function(jqXHR, textStatus, errorThrown) {
reject();
})
.done(function(responseJson1a) {
//Do stuff to populate numExeDetails and exercises[]
alert(numExeDetails);//Displays correct value
alert(exercises[0]);//Displays correct value
alert(exercises[1]);//Displays correct value
resolve(numExeDetails, exercises);
});
});
});
function loadExerciseDetails(numExeDetails, exercises) {
//Do more stuff
});
CodePudding user response:
Long story short, you can pass only one argument to resolve
.
Instead of doing resolve(numExeDetails, exercises)
do resolve({ numExeDetails, exercises })
, and then you can read it like .then(({ numExeDetails, exercises }) => {
.
There are other issues in your example, like exerciseFirstColumnDetails
not returning an actual promise. Will pretend the example is just incomplete.
CodePudding user response:
You need to return a promise in order to use .then()
.
The wasiest way to do this is by using return Promise.resolve()
.
function exerciseFirstColumnDetails() {
const numExeDetails = 0;
const exercises = [];
return Promise.resolve({numExeDetails, exercises});
};
function manipulateData({numExeDetails, exercises}){
return Promise.resolve({
numExeDetails,
exercises: [...exercises, 123, 456, 789],
});
}
exerciseFirstColumnDetails()
.then(manipulateData)
.then(console.log);