Quantcast
Channel: SharePoint 2013 - Development and Programming forum
Viewing all articles
Browse latest Browse all 7589

Asynchronous JavaScript: Getting JavaScript Promise to Work in For Loop

$
0
0

While this is a basic JavaScript question, it is related to my SharePoint-hosted app development.

In using JavaScript promises in a for loop, I get the general idea that an array
must be generated by the for loop and then the asynchronous calls are set as
each element in that array. So why isn't my Promise.all() working?

The code below is a very abbreviated example of the principle I am applying.
The important point here is that a method in an object ("class") is the asynchronous call.
My main process will create 3 instances of the object MyClassA. Each instance is
stored in an array with the asynchronous method called.

When I then pass the array the Promise.all() method, the argument to the .then() method
is the result array with all elements undefined. Not supposed to happen.

I have tried 50 different variations of code to try to get this to work, all of them learning processes
in how asynchronous JavaScript is supposed to work.

function myClassA () { this.myAsynchronousMethod = function (arg) { return new Promise( function (resolve, reject) { //some processing resolve (anAnswer); // omitting reject case in this (I check for errors) }; }; } function main () { var i,
action = [ ],
someObjectInstance = new myClassB(); // myClassB not shown

for (i = 0; i < 3; i++) action.push((new myClassA()).myAsynchronousMethod(someObjectInstance));

Promise.all(action).then( function (response) { // 'response' is always an array of ALL undefined elements for (i = 0; i < 3; i++) workOn(response[i]); }); }




Viewing all articles
Browse latest Browse all 7589

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>