phymooc / learn-javascript

0 stars 0 forks source link

Promise #6

Open phymo opened 2 years ago

phymo commented 2 years ago

module.exports = PromiseSimple

phymo commented 2 years ago

console.log(PromiseSimple);

fakeApiBackend = () => { const user = { userName: 'user', password: 'password', profile: 'ssssssssssssss', };

if (Math.random() > 0.1) { return { data: user, statusCode: 200, }; } else { return { error: 'error', message: 'error, please try later', statusCode: 500, }; } }

const makeApiCall = () => { return new PromiseSimple((resolve, reject) => { setTimeout(() => { const response = fakeApiBackend();

  if (response.statusCode === 200) {
    resolve(response.data);
  } else {
    reject(response);
  }
}, 3000);

}) }

makeApiCall() .then((data) => { console.log(data); return data; }).then((data) => { console.log(data); }).catch((error) => { console.log(error); });

phymo commented 6 months ago

https://www.lydiahallie.com/blog/promise-execution Long story short, Promises are just objects with some additional functionality to change their internal state.

phymo commented 4 months ago

Promises From The Ground Up https://www.joshwcomeau.com/javascript/promises/