Categories
JavaScript Answers

How to Wait Until All Promises Complete Even If Some Are Rejected?

Sometimes, we may want to wait until all promises to complete but we may want to proceed regardless of whether some promises are rejected or not.

In this article, we’ll look at how to wait until all promises are completed even if some are rejected.

Promise.allSettled

The Promise.allSettled method lets us proceed with running the then callback regardless of whether all promises are complete.

For instance, we can write:

Promise.allSettled([
  Promise.resolve(1),
  Promise.resolve(2),
  Promise.reject(3),
]).then(([result1, result2, result3]) => {
  console.log(result1, result2, result3)
});

Then result1 is {status: “fulfilled”, value: 1} .

result2 is {status: “fulfilled”, value: 2} .

And result3 is {status: “rejected”, reason: 3} .

status has the status of each promise.

And value has the resolved value if the promise is resolved.

And reason has the rejected value if the promise is rejected.

We can also write the same code with the async and await syntax.

For instance, we can write:

(async () => {
  const [result1, result2, result3] = await Promise.allSettled([
    Promise.resolve(1),
    Promise.resolve(2),
    Promise.reject(3),
  ])
  console.log(result1, result2, result3)
})()

And we get the same values as before for result1 , result2 , and result3 .

Promise.all with map

We can call map on the promise array.

Then we pass in a callback that calls catch on any promise that are rejected.

The catch callback only runs when a promise is rejected, so we either return the promise itself if catch isn’t run.

Otherwise, we return a promise with the catch callback run.

So we can write:

Promise.all(
    [
      Promise.resolve(1),
      Promise.resolve(2),
      Promise.reject(3),
    ]
    .map(p => p.catch(e => e))
  )
  .then(([result1, result2, result3]) => {
    console.log(result1, result2, result3)
  });

We call map with p => p.catch(e => e) to return any promises that are rejected with a promise that’s caught.

In the catch callback, we return the rejection reason.

Then in the then callback, we can destructure the promise results as usual.

So we get that result1 is 1.

result2 is 2.

And result3 is 3.

We can write tyhe same code with async and await by writing:

(async () => {
  const [result1, result2, result3] = await Promise.all([
      Promise.resolve(1),
      Promise.resolve(2),
      Promise.reject(3),
    ]
    .map(p => p.catch(e => e))
  )
  console.log(result1, result2, result3)
})()

And we get the same result as before.

Conclusion

The Promise.allSettled method is the best way to run code after a promise is run regardless of the outcomes of the promises that are run.

If we don’t want to use that, we can also use Promise.all with map and catch .

Categories
JavaScript Answers

How to Set the Value of an Input Field with JavaScript?

One way to set the value of an input field with JavaScript is to set the value property of the input element.

For instance, we can write the following HTML:

<input id='mytext'>

Then we can set the value property of the input by writing:

document.getElementById("mytext").value = "My value";

Call the setAttribute Method

Also, we can call the setAttribute method to set the value attribute of the input element.

For instance, we can write:

document.getElementById("mytext").setAttribute('value', 'My value');

We call setAttribute with the attribute name and value to set the value attribute to 'My value' .

Setting the value Property of an Input in a Form

We can also get the input element by using the document.forms object with the name attribute value of the form and the name attribute value of the input element.

For example, we can write the following HTML:

<form name='myForm'>
  <input type='text' name='name' value=''>
</form>

Then we can use it by writing:

document.forms.myForm.name.value = "New value";

The form name value comes first.

Then the name value of the input element comes after it.

document.querySelector

We can use the document.querySelector method to select the input.

For instance, we can write the following HTML:

<input type='text' name='name' value=''>

Then we can write:

document.querySelector('input[name="name"]').value = "New value";

to get the element with querySelector .

We select the input with the name attribute by putting the name key with its value in the square brackets.

Categories
JavaScript Answers

How to Get a Key in a JavaScript Object by its Value?

Sometimes, we may want to get the key of a JavaScript object by its value.

In this article, we’ll look at how to get a key in a JavaScript object by its value.

Object.keys and Array.prototype.find

We can use the Object.keys method to return an array of non-inherited string keys in an object.

And we can use the JavaScript array’s find method to return the first instance of something that meets the given condition in an array.

For instance, we can write:

const object = {
  a: 1,
  b: 2,
  c: 3
}
const value = 2;
const key = Object.keys(object).find(key => object[key] === value);
console.log(key)

We have the object object that we want to search for the key in.

And value is the value of the key that we want to search for.

We get all the keys of object with Object.kets .

Then we call find with a callback that returns object[key] === value .

key is the object key being iterated through to find the key name for the given value .

Therefore, we should see that key is 'b' from the console log.

Object.keys and Array.prototype.filter

We can replace the find with filter and destructure the result from the array returned by filter .

For instance, we can write:

const object = {
  a: 1,
  b: 2,
  c: 3
}
const value = 2;
const [key] = Object.keys(object).filter(key => object[key] === value);
console.log(key)

And we get the same result for key as in the previous example.

Object.entries and Array.prototype.find

We can use the Object.entries method to return an array of arrays of key-value pairs of an object.

Therefore, we can use the returned array to find the key of the object with the given value.

For instance, we can write:

const object = {
  a: 1,
  b: 2,
  c: 3
}
const value = 2;
const [key] = Object.entries(object).find(([, val]) => val === value);
console.log(key)

We call find with a callback that has the parameter with the val variable destrutured from the parameter.

val has the value of the in the key-value pair array.

So when we return val === value , we return the same boolean expression as the first example.

From the returned result of find , we can get the key of from the returned key-value pair by destructuring it.

And so we get the same value of key logged in the console log.

Conclusion

We can find a key that has the given value by using native JavaScript object methods.

Categories
JavaScript Answers

How to Set the Value of an Input Field with JavaScript?

One way to set the value of an input field with JavaScript is to set the value property of the input element.

For instance, we can write the following HTML:

<input id='mytext'>

Then we can set the value property of the input by writing:

document.getElementById("mytext").value = "My value";

Call the setAttribute Method

Also, we can call the setAttribute method to set the value attribute of the input element.

For instance, we can write:

document.getElementById("mytext").setAttribute('value', 'My value');

We call setAttribute with the attribute name and value to set the value attribute to 'My value' .

Setting the value Property of an Input in a Form

We can also get the input element by using the document.forms object with the name attribute value of the form and the name attribute value of the input element.

For example, we can write the following HTML:

<form name='myForm'>
  <input type='text' name='name' value=''>
</form>

Then we can use it by writing:

document.forms.myForm.name.value = "New value";

The form name value comes first.

Then the name value of the input element comes after it.

document.querySelector

We can use the document.querySelector method to select the input.

For instance, we can write the following HTML:

<input type='text' name='name' value=''>

Then we can write:

document.querySelector('input[name="name"]').value = "New value";

to get the element with querySelector .

We select the input with the name attribute by putting the name key with its value in the square brackets.

Categories
JavaScript Answers

How to Get the Last Item in a JavaScript Object?

Sometimes, we want to get the last item in a JavaScript object.

In this article, we’ll look at how to get the last item in a JavaScript object.

Get the Last Item in a JavaScript Object

To get the last item in a JavaScript object, we can use the Object.entries method to get the key-value pair arrays of an object in an array.

Therefore, we can use it to get the last item of the JavaScript object.

For instance, we can write:

const obj = {
  'a': 'apple',
  'b': 'banana',
  'c': 'carrot'
}
const entries = Object.entries(obj)
const [last] = entries.slice(-1)
console.log(last)

We have the obj object that we want to get the last property from.

Next, we call Object.entries with obj to get an array of key-value pair arrays of obj .

Then we call slice with -1 to return an array with the last entry of entries .

And we destructure that and assign it to last .

Therefore, last is:

["c", "carrot"]

Conclusion

To get the last item in a JavaScript object, we can use the Object.entries method to get the key-value pair arrays of an object in an array.

Therefore, we can use it to get the last item of the JavaScript object.