By promises
- Define a promise:
- establish a method: promise.then(…..after promise is completed)
let lazy = new Promise(resolve=>setTimeout(()=>resolve(‘I am lazy’) ,1000))
lazy.then(result => console.log(result) )
in place of setTimeout there can be a matrix calculation or a network request
without arrow function parent’s ‘this’ context won’t be passed
___________________________________________________________________
By async and await
- function should be marked as an async function
- define your lazy function function as a promise and mark the line as await
async function asyncCall() {
for(i=1; i<=10; i++){
await new Promise(resolve=>setTimeout(()=>resolve(console.log(i)) ,100))
}
}
asyncCall()