Uri Gross
Uri Gross

Reputation: 524

node.js / promises / Error message: ...is not a function

I am trying to run a simple 2 file node.js project. Project is running a problem and prints an error message "TypeError: steamBroccoli is not a function". I removed the braces from steamBroccoli() - It worked, The project ran without errors. But I don't know how it ran like that and I don't know why it pointed that problem as steamBroccoli is a function.

library.js

let cookBeans = () => {
return new Promise ((resolve, reject) => {
 setTimeout(()=>{
   resolve('beans')
 }, 1000)
})
}

let steamBroccoli = () => {
return new Promise ((resolve, reject) => {
 setTimeout(()=>{
   resolve('broccoli')
 }, 1000)
})
}

let cookRice = () => {
return new Promise ((resolve, reject) => {
 setTimeout(()=>{
   resolve('rice')
 }, 1000)
})
}

let bakeChicken = () => {
return new Promise ((resolve, reject) => {
 setTimeout(()=>{
   resolve('chicken')
 }, 1000)
})
}

module.exports = {cookBeans, steamBroccoli, cookRice, bakeChicken}
let {cookBeans, steamBroccoli, cookRice, bakeChicken} = require('./library.js')

async function serveDinner(){
  const vegetablePromise = steamBroccoli(); // If I remove the braces  - The error disappear and the code works.  
  const starchPromise = cookRice();
  const proteinPromise = bakeChicken();
  const sidePromise = cookBeans();
  console.log(`Dinner is served. We're having ${await vegetablePromise}, ${await starchPromise}, ${await proteinPromise}, and ${await sidePromise}.`)
}
serveDinner();

Upvotes: 0

Views: 119

Answers (1)

jasonandmonte
jasonandmonte

Reputation: 2028

Your example code works! Since you are using arrow functions you can refactor your promises to remove some of the boilerplate code.

const steamBroccoli = () => new Promise((resolve) => {
  setTimeout(() => resolve('broccoli'), 1000);
});

Upvotes: 1

Related Questions