3

I am creating an array, after it is created that array is resolved as a Object. However as I need to sort tempArray based on a particular value after the resolve I need it as an array, not an Object. Also because after the sort I am displaying it using: *ngFor. Or is it better to somehow sort the Object instead of changing it back to an array?

The console.log of the returned Promise is displayed underneath.

var tempArray = []
return new Promise((resolve, reject) => {
  let error = false;
  var i = 0;
  for (let key of arrayOfPosts) {
    tempArray[i] = {
      "_id": key._id,
      "postPub": key.postPub,
      "timePast": this.timePastPublix
    }
    i++
  }

  if (error) {
    reject('error')
  } else {
    resolve(tempArray)
  }
});

{_id: "5aba1af4c97ce42ea81893bc", postPub: "0.00", timePast: "1970-01-01T01:00:00+01:00"}
{_id: "5ac698172910d705ecd66378", postPendingPayoutPublic: "0.00", timePast: "1970-01-01T01:00:00+01:00"}

1 Answer 1

7

You can just return it as an array, no need for an Object:

var promise = new Promise((resolve, reject) => {
  resolve([1,2,3,4,5]);
});

// reject example
var promise2 = new Promise((resolve, reject) => {
  var array = [];
  if(array.length == 0)
     reject("error");
  else
     resolve(array);
});

promise.then(data => console.log(data));
promise2.then(data => console.log(data))
        .catch(error => console.log(error));

Here is a stackblitz which uses the promise array return values in an *ngFor: https://stackblitz.com/edit/angular-vpkk1a

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

4 Comments

It's Promise.resolve(array). No need for promise construction function.
@estus You are correct, my example could be just that, however in the question it appears like they want some sort of error checking to take place within the promise.
When would we check for rejects, could you give an example? Your solution works.
@oudekaas Added an example which churns out an error.

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.