Javascript syntax using await Promise.all [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am trying to understand the below code/syntax which uses await Promise.all;
How is the array getting assigned from the endpoint response ?
const getState = async (code) => {
try {
const [
{data: dataResponse},
{data: stateDistrictWiseResponse},
{data: statesDailyResponse},
{data: stateTestResponse},
{data: sourcesResponse},
{data: zonesResponse},
] = await Promise.all([
axios.get('https://example.org/data.json'),
axios.get('https://example.org/state_district_wise.json'),
axios.get('https://example.org/states_daily.json'),
axios.get('https://example.org/state_test_data.json'),
axios.get('https://example.org/sources_list.json'),
axios.get('https://example.org/zones.json'),
]);
console.log(stateTestResponse.states_tested_data);
}
}

Promise.all converts an array of promises into an array of results.
axios.get returns a promise that, when resolved, returns an object with the shape { data: <result goes here>
Your code is destructuring those objects within the returned array.

Related

How do I consume an asynchronous response twice [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm looking for best nodeJS practice to consume the result of an asynchronous operation in two places.
I currently have the following pseudo-code
async function doSomething() {
const something = await fetchSomething();
console.log("something", something); // (A)
}
function fetchSomething() {
const promise = fetch("http://example.com/something");
/* new code to update something will live here (B) */
return promise;
}
So far so good
I now need to do make a change to update something within fetchSomething() at the line new code will live here. The new code will be something like something.timestamp = new Date();
How can I access something within fetchSomething() and be sure that the update I make to something at (B) occurs before I log something at (A).
Just convert your fetchSomething to also be async:
async function doSomething() {
const something = await fetchSomething();
console.log("something", something); // (A)
}
async function fetchSomething() {
const something = await fetch("http://example.com/something");
/* new code to update something will live here (B) */
something.someOtherThing = 'updated something!';
return something;
}
Every async function returns a Promise so you can just await it again.

Should a Javascript function avoid reject a promise via a ternary condition? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I saw a piece of code that looks funny to me. It feels like there are multiple things wrong here. Am I seeing a ternary here returning an error rather than a value? Shouldn't this therefore be an if-else?
const aData = await response.json();
return await new Promise((resolve, reject) => {
(aData.title === aName)
? resolve('A data was found')
: reject(new Error('Incorrect data was returned'));
});
Both resolve and reject just return the value undefined, and your callback function doesn't return anything at all. Using a ternary operator to make it a single expression is rather useless.
For clarity, you should better write
if (aData.title === aName) resolve('A data was found');
else reject(new Error('Incorrect data was returned'));
although really you shouldn't be using the new Promise constructor here at all. Just
const aData = await response.json();
if (aData.title !== aName) throw new Error('Incorrect data was returned');
else return 'A data was found';

Is Nesting Promises Bad Practice? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I know my code has the correct logic, but everywhere I look I'm told not to use nested promises. Is this a use case for nested promises?
The logic is as follows:
promise1 fails -> reverse promise1
promise1 succeeds -> promise2/promise3 fails -> reverse promise1,
promise2, promise 3
promise1 succeeds -> promise2 & promise3 succeeds
let data = null;
promise1.then((response) => {
data = response;
return Promise.all([promise2(), proimse3()])
.catch((error) => {
//Reverse only promise2, promise3
//Throw error to reverse promise1
});
}).then((id) => {
something(data);
}).catch((error) => {
//Reverse only promise1
});

How can we use promise in node.js packages [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
When we write a module for node.js, we use callback functions. I learned promises in javascript and I want to use in node.js module. Can we use promises instead of callback functions ? if we can, how ?
note : via function in node module file ( you know exports.some_func ) , we do somethings and we can send back informations with callback . Can we use promise instead of that callback ?
Can we use promise instead of that callback ?
Yes, rather than accepting a callback in your exported function, you can just return a promise and make sure that promise is resolved/rejected with the proper value/reason when the async operation is done.
Here's an example:
Imagine you have a module interface for reading a file, then you can have that interface return a promise like this:
// myFileModule.js
const fs = require('fs');
module.exports.getFile = function(filename, options) {
return new Promise(function(resolve, reject) {
fs.readFile(filename, options, function(err, data) {
if (err) return reject(err);
resolve(data);
});
});
}
The caller would then use it like this:
const myFiles = require('myFileModule.js');
myFiles.getFile('temp.txt').then(function(data) {
// process data here
}, function(err) {
// got an error here
});

Javascript scope in promises [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
How can I access to the user object in the promises callback ?
I try to bind it with no success.
const promises = User.find(req.user._id).exec();
promises.then(function (user) {
noAccessFunction().then(function (customer) {
// HERE
user.save();
});
});
Promises are not callbacks! Mutate it as if it were a chain of values. Maybe something like this:
const promises = User.find(req.user._id).exec();
promises.then(function (user) {
return myfunction().then(function (customer) {
return user.save();
});
});
Promises can also be flattened:
const promises = User.find(req.user._id).exec();
promises.then(function (user) {
return myfunction(user);
})
.then(function (customer) {
return customer.save();
});
In any case the code above is speculation since you have not provided enough information as to what you want to happen.

Categories

Resources