Suppose I have two promises. Normally, the code cannot execute until all these promise are finished. In my code, suppose I have promise1 and promise 2
then I have await promise1 and await promise2. My code won't execute until both these promise are finished. However what I need is that if one of these two is finished then the code can execute and then we can ignore the other one.
That is possible because the code only needs one of these awaits to succeed. Is this possible to implement in javascript (nodejs) ?
Promise.any is what you're looking for:
Promise.any() takes an iterable of Promise objects. It returns a single promise that resolves as soon as any of the promises in the iterable fulfills, with the value of the fulfilled promise. If no promises in the iterable fulfill (if all of the given promises are rejected), then the returned promise is rejected with an AggregateError, a new subclass of Error that groups together individual errors.
Example:
const randomDelay = (num) => new Promise((resolve) => setTimeout(() => {
console.log(`${num} is done now`);
resolve(`Random Delay ${num} has finished`);
}, Math.random() * 1000 * 10));
(async() => {
console.log("Starting...");
const result = await Promise.any(new Array(5).fill(0).map((_, index) => randomDelay(index)));
console.log(result);
console.log("Continuing...");
})();
You can use Promise.any() function. You can pass an array of Promises as an input, and it will resolve as soon as first Promise resolves.
(async() => {
let promises = [];
promises.push(new Promise((resolve) => setTimeout(resolve, 100, 'quick')))
promises.push(new Promise((resolve) => setTimeout(resolve, 500, 'slow')))
const result = await Promise.any(promises);
console.log(result)
})()
Promise.race() or Promise.any()
If one of the promises's status changed whatever rejected or fulfilled, you can use Promise.race()
If you want one of the promises to be fulfilled, you should use
Promise.any()
Promise.any can continue to execute other code if any One Promise will resolved.
let i = 1;
const newPromise = () => {
return new Promise((resolve) => {
setTimeout(() => {
console.log(`promise${i++} resolved`);
resolve(true);
}, Math.random() * 1000)
});
}
(async() => {
await Promise.any([newPromise(), newPromise()]);
console.log("Code will executes if any promise resolved");
})()
Related
I just wanted to know if it is considered good practice to nest promises like in this example, or is there better alternatives ?
getDatabaseModel.searchId(idNoms).then(function([noms, elements]) {
getDatabaseModel.getLocalisations().then(function(localisations){
getDatabaseModel.getStates().then(function(states){
//Some code
})
})
})
Obviously, your promises are independent. So you should use Promise.all() to make it run parallel with the highest performance.
The Promise.all() method takes an iterable of promises as an input,
and returns a single Promise that resolves to an array of the results
of the input promises
var searchById = getDatabaseModel.searchId(idNoms);
var getLocalisations = getDatabaseModel.getLocalisations();
var getStates = getDatabaseModel.getStates();
var result = Promise.all([searchById, getLocalisations, getStates]);
result.then((values) => {
console.log(values);
});
For example, Let's say each promise takes 1s - So it should be 3s in total, But with Promise.all, actually it just takes 1s in total.
var tick = Date.now();
const log = (v) => console.log(`${v} \n Elapsed: ${Date.now() - tick}`);
log("Staring... ");
var fetchData = (name, ms) => new Promise(resolve => setTimeout(() => resolve(name), ms));
var result = Promise.all(
[
fetchData("searchById", 1000),
fetchData("getLocalisations", 1000),
fetchData("getStates", 1000)
]);
result.then((values) => {
log("Complete...");
console.log(values);
});
Besides, If you're concern about asyn/await with more elegant/concise/read it like sync code, then await keyword much says the code should wait until the async request is finished and then afterward it'll execute the next thing. While those promises are independent. So promise.all is better than in your case.
var tick = Date.now();
const log = (v) => console.log(`${v} \n Elapsed: ${Date.now() - tick}`);
var fetchData = (name, ms) => new Promise(resolve => setTimeout(() => resolve(name), ms));
Run();
async function Run(){
log("Staring... ");
var a = await fetchData("searchById", 1000);
var b = await fetchData("getLocalisations", 1000);
var c = await fetchData("getStates", 1000);
log("Complete...");
console.log([a, b, c]);
}
Promises were made to avoid callback hell, but they are not too good at it too. People like promises until they find async/await. The exact same code can be re-written in async/await as
async getModel(idNoms){
const [noms, elements] = await getDatabaseModel.searchId(idNoms);
const localisations = await getDatabaseModel.getLocalisations();
const state = await getDatabaseModel.getStates():
// do something using localisations & state, it'll work
}
getModel(idNoms);
Learn async/await here
IMO it's a little hard to read and understand. Compare with this:
getDatabaseModel.searchId(idNoms)
.then(([noms, elements]) => getDatabaseModel.getLocalisations())
.then(localization => getDatabaseModel.getStates());
As #deceze pointed out there are two things to note:
These functions are called serially
They don't seem to depend on each other as the noms, elements and localization are not used at all.
With Promise.all you can mix and match however you want:
// Call `searchId` and `getState` at the same time
// Call `getLocalisations` after `searchId` is done
// wait for all to finish
Promise.all([
getDatabaseModel.searchId(idNoms).then(([noms, elements]) => getDatabaseModel.getLocalisations()),
getDatabaseModel.getStates()
]).then(([result1, result2]) => console.log('done'));
// Call all 3 at the same time
// wait for all to finish
Promise.all([
getDatabaseModel.searchId(idNoms),
getDatabaseModel.getLocalisations(),
getDatabaseModel.getStates(),
]).then(([result1, result2, result3]) => console.log('done'));
I am using Promises and in the meanwhile i have a loading animation.
the problme is that my promise is resolved fast and the loader is quickly disappear.
So i want to launch a promise and if the promise is resolved before 3 sec wait the remaining time.
Example
export const operation = () => {
const a = new Date();
const myPromise = doAction().then(() => {
const b = new Date();
if((b - a) < 3000)
operationIsDone();
else
setTimeout(() => {operationIsDone();}, b - a)
});
}
Is there any npm or a better way doing it?
Thanks in advance.
It is much easier to use a second promise that just runs the minimum waiting time. Then use Promise.all to wait for both to finish.
That way, your script will always wait at least the default delay but also longer if yourOwnPromise takes longer than that.
const wait = delay => new Promise(resolve => setTimeout(resolve, delay));
const doAction = () => wait(500); // TODO replace this with your own function
const yourOwnPromise = doAction();
yourOwnPromise.then(() => {
console.log('yourOwnPromise resolved now');
});
Promise.all([yourOwnPromise, wait(3000)]).then(() => {
console.log('both resolved now');
});
See Promise.all for details.
I have three promises. I need to combine them together to create one more promise.
Something like this Promise.all('url1','url2','url3') or if there is other possible way to achieve it.
Intent is to fire all of them in parallel.
I have requirement that when either two of them are resolved, then the final one will be resolved.
How I can achieve it?
The following might give you an idea. You have the chance to run the first resolving promise and the last one. But the logic is straightforward and you may play as you wish. I haven't included the error handling rejection logic but that should be fairly easy.
The bring() function returns a promise resolving in 100~200ms.
var bring = n => new Promise(v => setTimeout(v,~~(Math.random()*100)+100,`from url_${n}`)),
pcnt = 0,
proms = Array.from({length: 10})
.map((_,i) => bring(i).then(v => ++pcnt === 1 ? (console.log(`Do stg with the 1st resolving promise ${v} immediately`), [pcnt,v])
: pcnt < proms.length ? console.log(`Do nothing with intermediate resolving promise ${v}`)
: (console.log(`Do stg with the last resolving promise ${v} finally\n`), [pcnt,v])
)
);
Promise.all(proms)
.then(vs => console.log("Or when all completes, deal with the values returned from the first and last promise\n",vs.filter(d => !!d)));
.as-console-wrapper {
max-height: 100% !important
}
So you want to come up with a promise that resolves when, for example, 2 of 3 promises resolve. Promise.all wouldn't be the right thing to use because, well, you aren't waiting for all the promises to resolve. You'd have to do it manually:
const resolveAfterSeconds = function(sec) {
return new Promise(res => {
setTimeout(res, sec * 1000)
})
}
new Promise((resolve) => {
const promises = [
resolveAfterSeconds(1),
resolveAfterSeconds(2),
resolveAfterSeconds(3),
];
let resolveCount = 0;
promises.forEach(prom => {
prom.then(() => {
console.log('resolving');
resolveCount++;
if (resolveCount === promises.length - 1) resolve();
});
});
}).then(() => console.log('done'));
I have the following code
module.exports = async function (req, res) {
const station1 = await getStation('one')
const station2 = await getStation('two')
return { stations: [station1, station2] }
}
Can I be guaranteed that when the final return value is sent it will definitely have both station1 and station2 data in them, or do I need to wrap the function call in a Promise.all()
As you have it, it is guaranteed that the return statement will only be executed when the two getStation() promises have resolved.
However, the second call to getStation will only happen when the first promise has resolved, making them run in serial. As there is no dependency between them, you could gain performance, if you would run them in parallel.
Although this can be achieved with Promise.all, you can achieve the same by first retrieving the two promises and only then performing the await on them:
module.exports = async function (req, res) {
const promise1 = getStation('one');
const promise2 = getStation('two');
return { stations: [await promise1, await promise2] }
}
Now both calls will be performed at the "same" time, and it will be just the return statement that will be pending for both promises to resolve. This is also illustrated in MDN's "simple example".
The await keyword actually makes you "wait" on the line of code, while running an async action.
That means that you don't proceed to the next line of code until the async action is resolved. This is good if your code has a dependency with the result.
Example:
const res1 = await doSomething();
if(res1.isValid)
{
console.log('do something with res1 result');
}
The following code example will await a promise that gets resolved after three seconds. Check the date prints to the console to understand what await does:
async function f1() {
console.log(new Date());
// Resolve after three seconds
var p = new Promise(resolve => {
setTimeout(() => resolve({}),3000);
});
await p;
console.log(new Date());
}
f1();
ES6Console
BTW, In your case, since you don't use the result of station1 it's better using Promise.all to work parallel.
Check this example (it will run for 3 seconds instead of 4 seconds the way you coded above):
async function f1() {
console.log(new Date());
// Resolve after three seconds
var p1 = new Promise(resolve => {
setTimeout(() => resolve({a:1}),3000);
});
// Resolve after one second
var p2 = new Promise(resolve => {
setTimeout(() => resolve({a:2}),1000);
});
// Run them parallel - Max(three seconds, one second) -> three seconds.
var res = await Promise.all([p1,p2]);
console.log(new Date());
console.log('result:' + res);
}
f1();
ES6Console.
If either of await getStation('one') or await getStation('two') fails an exception will be thrown from the async function. So you should always get the resolved value from both promises.
You can rewrite your function as follows to use Promise.all
module.exports = async function (req, res) {
try{
const [station1, station2] = await Promise.all([
getStation('one'),
getStation('two')
]);
return { stations: [station1, station2] };
} catch (e) {
throw e;
}
}
Using Node 4.x. When you have a Promise.all(promises).then() what is the proper way to resolve the data and pass it to the next .then()?
I want to do something like this:
Promise.all(promises).then(function(data){
// Do something with the data here
}).then(function(data){
// Do more stuff here
});
But I'm not sure how to get the data to the 2nd .then(). I can't use resolve(...) in the first .then(). I figured out I can do this:
return Promise.all(promises).then(function(data){
// Do something with the data here
return data;
}).then(function(data){
// Do more stuff here
});
But that doesn't seem like the proper way to do it... What is the right approach to this?
But that doesn't seem like the proper way to do it..
That is indeed the proper way to do it (or at least a proper way to do it). This is a key aspect of promises, they're a pipeline, and the data can be massaged by the various handlers in the pipeline.
Example:
const promises = [
new Promise(resolve => setTimeout(resolve, 0, 1)),
new Promise(resolve => setTimeout(resolve, 0, 2))
];
Promise.all(promises)
.then(data => {
console.log("First handler", data);
return data.map(entry => entry * 10);
})
.then(data => {
console.log("Second handler", data);
});
(catch handler omitted for brevity. In production code, always either propagate the promise, or handle rejection.)
The output we see from that is:
First handler [1,2]
Second handler [10,20]
...because the first handler gets the resolution of the two promises (1 and 2) as an array, and then creates a new array with each of those multiplied by 10 and returns it. The second handler gets what the first handler returned.
If the additional work you're doing is synchronous, you can also put it in the first handler:
Example:
const promises = [
new Promise(resolve => setTimeout(resolve, 0, 1)),
new Promise(resolve => setTimeout(resolve, 0, 2))
];
Promise.all(promises)
.then(data => {
console.log("Initial data", data);
data = data.map(entry => entry * 10);
console.log("Updated data", data);
return data;
});
...but if it's asynchronous you won't want to do that as it ends up getting nested, and the nesting can quickly get out of hand.
Today NodeJS supports new async/await syntax. This is an easy syntax and makes the life much easier
async function process(promises) { // must be an async function
let x = await Promise.all(promises); // now x will be an array
x = x.map( tmp => tmp * 10); // proccessing the data.
}
const promises = [
new Promise(resolve => setTimeout(resolve, 0, 1)),
new Promise(resolve => setTimeout(resolve, 0, 2))
];
process(promises)
Learn more:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
Your return data approach is correct, that's an example of promise chaining. If you return a promise from your .then() callback, JavaScript will resolve that promise and pass the data to the next then() callback.
Just be careful and make sure you handle errors with .catch(). Promise.all() rejects as soon as one of the promises in the array rejects.