A demo app for JavaScript Concept
- Clone this repo by running
git clone https://github.com/imranhsayed/javascript-concepts
cd javascript-concepts
cd branch-name
npm install
npm run server
1. callbacks
- Callbacks add complexity and readability issue. And its messy to chain the tasks
2. promises
- A promise is an object that represent the eventual( future ) completion(or failure) of an asynchronous operation, and its future result value.
Promises are thin abstraction around call backs. ( e.g.
readFile.( 'config.json' ).then(...).catch(...)
) In below example what you pass in resolve will be available as value in.then(( value )=> ...)
var promise1 = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('foo');
}, 300);
});
promise1.then(function(value) {
console.log(value);
// expected output: "foo"
});
- Automatically transforms a regular function into a Promise.
- When called async functions resolve with whatever is returned in their body.
- Async functions enable the use of
await
.
- When placed in front of a Promise call, await forces the rest of the code to wait until that Promise finishes and returns a result.
- Await works only with Promises, it does not work with callbacks.
- Await can only be used inside async functions.
async function getTodoData() {
const todoData = await fetch( 'https://jsonplaceholder.typicode.com/todos/' );
return todoData;
}
getTodoData()
.then( res => res.json() )
.then( ( result ) => {
console.warn( result );
} );
async function getPosts() {
try {
const postsData = await await fetch( 'https://jsonplaceholder.typicode.com/posts/' );
return postsData;
}
catch ( error ) {
console.warn( 'error', error );
}
}
getPosts()
.then( res => res.json() )
.then( ( result ) => {
console.warn( result );
} );
fetch('https://example.com/wp-json/wp/v2/posts')
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
// Examine the text in the response
response.json().then(function(data) {
console.log(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
npm run dev
starts a webpack dev server at http://localhost:8080npm run prod
runs build for production in dist directory.
- Node
- Express
- ES6
- Webpack
- Babel