Answer the question
In order to leave comments, you need to log in
How to get the results of the first few Promises executed?
Given:
React project, in short there is a search bar. During the input of the value, AJAX-s are triggered in order to get hints (suggestions) in the amount of 8-10 pieces for different data sources.
Problem:
You need to show the result of two ajaxes that arrived faster, and cancel all the rest.
Now it works on Promise.all , which waits for all promises to be fulfilled, it does not fit.
I know that there is a Promise.race method , but it only waits for the first ajax (this is a little closer to what I need).
Is there a solution to this problem in JS or do I need to write a crutch? If a crutch, then please write an example, add the implementation:
const ajax1 = new Promise((res, rej) => setTimeout(() => res({ data1: 'work'}), 3000));
const ajax2 = new Promise((res, rej) => setTimeout(() => res({ data2: 'work'}), 6000));
const ajax3 = new Promise((res, rej) => setTimeout(() => res({ data3: 'work'}), 1000));
const ajax4 = new Promise((res, rej) => setTimeout(() => res({ data4: 'work'}), 5000));
let result = {};
// .... реализация
console.log(result); // { data3: 'work', data1: 'work' }
Answer the question
In order to leave comments, you need to log in
function getFisrtPromises(promises, count) {
return new Promise(resolve => {
const results = [];
const onResolve = result => {
results.push(result);
if (results.length === count || results.length === promises.length) {
resolve([...results]);
}
};
promises.forEach(n => n.then(onResolve));
});
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question