Forum Discussion
Problem SPFx - Javascript - Ajax
- Aug 20, 2018
Hi Fernanda,
You basically have an issue with asynchronous code.
You will have to use promises or async await (which is a super simple abstraction of promises) in order to control the execution of your code and ensure that the code "waits" for the results to be returned by the ajax call before continuing.
Using async/await, you will need to change your function to something like the code below (it's using an arrow function, but you don't need to if you don't want). The 'async' word on the function declaration is the key here. This allows you to call the function using 'await' to ensure that the code "waits" for the promise to be returned.
this.array = await _content.getContent();
Sample function that performs an ajax call:
request = async (options: AJAXOptions): Promise<any> => {try {const ajaxRequest: any = await $.ajax({url: options.url,type: options.method,data: options.data,headers: options.headers,cache: false,});// return promisereturn ajaxRequest;} catch (error) {Utils.logError(error);}}Hope this helpsJoel
Hi Fernanda,
You basically have an issue with asynchronous code.
You will have to use promises or async await (which is a super simple abstraction of promises) in order to control the execution of your code and ensure that the code "waits" for the results to be returned by the ajax call before continuing.
Using async/await, you will need to change your function to something like the code below (it's using an arrow function, but you don't need to if you don't want). The 'async' word on the function declaration is the key here. This allows you to call the function using 'await' to ensure that the code "waits" for the promise to be returned.
this.array = await _content.getContent();
Sample function that performs an ajax call: