array [4,2,7,1] Create a function that returns a Promise. The promise will calculate the sum of an array and print it after 3 seconds

Viewed 49

This is what i tried - didnt work for me , and how i solve this using async-await ?

var array = [4, 2, 7, 1];

var prom = new Promise(function(myRsolve, myReject) {
  var sum = array.reduce((x, y) => x + y);
  
  setTimeout(function() {
    myResolve(sum);
  }, 3000);
  
  prom.then(function(value) {
    document.getElementById("tot").innerHTML = value;
  })
});
<p>Array total 4+2+7+1: </p>
<h2 id="tot"></h2>

1 Answers

This is the correct syntax for declaring a promise:

let promise = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('Resolved in 2000ms');
    }, 2000)
})

So in your case promise will be like this:

var array = [4, 2, 7, 1];

// Will resolve after 3000ms
let prom = new Promise((resolve, reject) => {
    var sum = array.reduce((x, y) => x + y);
    setTimeout(() => {
        resolve(sum);
    }, 3000)
})

prom.then(function (value) {
    document.getElementById("tot").innerHTML = value;
});
<p>Array total 4+2+7+1: </p>
<h2 id="tot"></h2>

Related