Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

Node.js util module

// typical Node.js error-first callback function
function getUser (id, callback) {
  return setTimeout(() => {
    if (id === 5) {
      callback(null, { nickname: 'Teddy' });
    } else {
      callback(new Error('User not found'));
    }
  }, 1000);
}
 
function callback (error, user) {
  if (error) {
    console.error(error.message);
    process.exit(1);
  }
  console.log(`User found! Their nickname is: ${user.nickname}`);
}
 
// change the getUser function into promise using `util.promisify()`
const getUserPromise = util.promisify(getUser);
 
// now you're able to use then/catch or async/await syntax
getUserPromise(id)
  .then((user) => {
      console.log(`User found! Their nickname is: ${user.nickname}`);
  })
  .catch((error) => {
      console.log('User not found', error);
  });
Comment

PREVIOUS NEXT
Code Example
Javascript :: javascript remove duplicates 
Javascript :: toarray javascript 
Javascript :: add array to array javascript 
Javascript :: nodejs delete s3 folder 
Javascript :: define an unsigned long int js 
Javascript :: plotly in react 
Javascript :: jquery find index of this 
Javascript :: settimeout in loop javascript 
Javascript :: cookie clicker hack extension 
Javascript :: jquery get duration video tag 
Javascript :: axios fetch 
Javascript :: npm install nodemon 
Javascript :: javascript generator function 
Javascript :: jquery detect textarea change 
Javascript :: jquery get dropdown list selected value 
Javascript :: bubble sort js 
Javascript :: js bubble sort 
Javascript :: node js post method 
Javascript :: node filesystem change directory of a file 
Javascript :: discord token 
Javascript :: set attribute javascript 
Javascript :: react chart js 2 
Javascript :: mongoose put request 
Javascript :: mapgetters with parameter 
Javascript :: array every javascript 
Javascript :: node js event emitter 
Javascript :: nodejs fs create file if not exists 
Javascript :: js iso date split 
Javascript :: set localstorage 
Javascript :: enzyme-adapter-react-17 
ADD CONTENT
Topic
Content
Source link
Name
6+2 =