Reputation: 4811
I have a few promises in my node server that after they all resolve the server renders to the client. I am using Promise.all([ ...
that has all the data from the few promises I have.
I now however need some data from another call before one of my promises resolves. But it seems Promise.all
is still resolving before I have what I need.
const myPromise = new Promise((resolve) => {
needDataFromThisCall(someInfo)
.then((data) => {
return resolve(sortData(data))
})
.catch((error) => {
//error handle
})
})
.then((resolvedData) => {
return resolvedData;
})
This does not seem to work because the final .then
the resolvedData is undefined
and seems to get resolved before I get into my sortData
function. Does the return resolve(sortData...
not end up giving its return value to the final .then
?
How should this really be done so myPromise
can resolve after I have that data needed to send to sortData
?
Upvotes: 0
Views: 64
Reputation: 5363
Below code works fine. Assuming sortData
is synchronous function, you need to resolve myPromise
to get the result.
let someInfo = [2,3,1];
let needDataFromThisCall = info => new Promise(res => setTimeout(()=>res(info), 500) );
let sortData = data => data.sort();
const myPromise = new Promise((resolve) => {
needDataFromThisCall(someInfo)
.then((data) => {
return resolve(sortData(data))
})
.catch((error) => {
//error handle
})
})
.then((resolvedData) => {
return resolvedData;
})
myPromise.then(data => console.log('final data', data))
Upvotes: 1