Reputation: 948
In the loop, I call the function and pass it the identifier, after which the function should return the vacancy to me.
const Profile = require('upwork-api/lib/routers/jobs/profile.js').Profile;
...
let jobsDetails = [];
for (let valueKeys of Object.values(arrayOfJobs)) {
getJobDitalis(api, valueKeys, (error, data) => {
console.log(data.profile)
jobsDetails.push(`${data.profile}`);
});
console.log(jobsDetails)
}
...
function getJobDitalis(api, key, callback) {
const profile = new Profile(api);
profile.getSpecific(key, (error, data) => {
callback(error, data);
});
}
But for some reason, first an empty object is displayed in the console, and then only information about the vacancy. That is, console.log (jobsDetails)
is fired first, and then only console.log (data.profile)
[]
[]
[]
{job}
{job}
{job}
Why it happens? What is my mistake?
Upvotes: 0
Views: 58
Reputation: 1023
Using async await you can make your async task synchronous.
I don't know about your code structure, but I tried to make a solution from the given data.
function getJobDitalis(api, key, callback) {
const profile = new Profile(api);
profile.getSpecific(key, (error, data) => {
callback(error, data);
});
}
...
(async ()=> {
let jobDetails = [];
for (let valueKeys of Object.values(arrayOfJobs)) {
const profile = await new Promise(resolve=>{
getJobDitalis(api, valueKeys, (error, data) => {
console.log(data.profile)
resolve(data.profile);
});
})
jobDetails.push(profile)
}
console.log(jobDetails);
//do your task with jobDetails
})()
I made IIFE async function.
Upvotes: 1
Reputation: 6206
Flow (let's assume a single iteration of the for
loop):
getJobDetalis(api, key, callback)
profile.getSpecific(key, func)
func(error, data)
callback(error, data)
console.log(data.profile)
console.log(jobsDetails)
However, profile.getSpecific
does not necessarily wait for func
to complete.
And since the 1st print is executed from the call-stack of func
, it will not necessarily occur before the 2nd print.
Upvotes: 0