0

I have this code:

var arrMultiplication = function(arr1, arr2) {
  return new Promise(function(resolve, reject) {

    if ( arr1.length ==arr2.length ) {
        temp =new Array();
        for(var i=0;i<arr1.length;i++){
        temp.push(arr1[i]*arr2[i]);
      }
      resolve(temp);
    } else {
      reject(Error("Promise Rejected"));
    }
  });
}
//[1,2,5], [1,2,0],[2,2,2].[1,2,3]
var A=[1,2,5];
var B=[1,2,0];
var C=[2,2,2];
var D=[1,2,3];
arrMultiplication(A,B).then(function(result){
    arrMultiplication(C,result).then(function(result){
    arrMultiplication(D,result).then(function(result){
        alert(result);
    });
  });
});

JSfiddle

How can I do it simpler instead of calling promise many times IF i have A B C D E F as arrays it will complex with this way. how to make it easier.

2
  • 1
    Why do you even use Promises anyway? There's no async code in there Commented Nov 15, 2018 at 15:53
  • I need to understand simplest way to use it, instead of coding complex coding,i would appreciate hints <3 Commented Nov 15, 2018 at 15:59

1 Answer 1

1

Although i agree with @szab comment that you don't need Promises here, in general terms you can use reduce to chain n-length promises.

Example:

var arrMultiplication = function(arr1, arr2) {
      return new Promise(function(resolve, reject) {
        
        if ( arr1.length ==arr2.length ) {
        	temp =new Array();
        	for(var i=0;i<arr1.length;i++){
          	temp.push(arr1[i]*arr2[i]);
          }
          resolve(temp);
        } else {
          reject(Error("Promise Rejected"));
        }
      });
    }
    //[1,2,5], [1,2,0],[2,2,2].[1,2,3]
    var A=[1,2,5];
    var B=[1,2,0];
    var C=[2,2,2];
    var D=[1,2,3];
    var allArrays = [A, B, C, D];
    
    const multiplicationsPromise = allArrays.reduce((resultPromise, currentArray) => {
    	return resultPromise.then(result => arrMultiplication(result, currentArray))	
    }, Promise.resolve([1,1,1]))
    
    multiplicationsPromise.then(result => alert(result));

Working fiddle here

Sign up to request clarification or add additional context in comments.

1 Comment

i agree with @szab too no need for promise here but im asking about logic that can be, and i think you answer explains everything <3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.