DEV Community

Jiwon Kim
Jiwon Kim

Posted on

Data Scientist Learning JS: Promises and resolve()

Context: I'm a data scientist/analyst (in Python and R) learning development from scratch. Inevitably, I am learning these through the lens of what I already know. If you have a similar background and are a beginner developer, I hope these analogies help! Any comments, especially if you spot any misunderstanding, are appreciated. Commenting is caring <3

Motivation: I was building a mock data layer for a fitness social app — simulating what happens when users fetch new posts from a feed. The function needs to return mock posts after a delay, simulating a real network request.

Working Code:

function fakeFetchPosts() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(posts);
    }, 2000);
  });
}

async function main() {
    console.log("Fetching...");
    const fetchedPosts = await fakeFetchPosts();
    console.log("Fetched posts:", fetchedPosts);

}

main();
console.log("Sync code ran");
Enter fullscreen mode Exit fullscreen mode

What do you expect to see as an output?

I first confused the logic with blocking. For example, in webscraping, something like time.sleep() or Selenium's WebDriverWait(driver, 10).until(EC.presence_of_element_located(...)). In this case, output will be Fetching..., Fetched posts: ..., then Sync code ran.

However, the output gives Fetching..., Sync code ran, and then Fetched posts. In the former, the whole script (single thread) pauses and does nothing else until the wait ends or the condition is met. The latter is different in that the rest of your program keeps running during the wait, and thus the output where Sync code ran is printed first before the fetchedPosts.

By the way, posts are arrays.

const posts = [{
    author: "j1wonkim",
    text: "Testing Physical",
    likes: 100,
},
{author: "onewc0218",
    text: "Love love",
    likes: 55,
},
{author: "gakbca",
    text: "You are good",
    likes: 10,
}
];
Enter fullscreen mode Exit fullscreen mode

You can find the same post here on my website.

Top comments (0)