What is Promise?
1. In ES6, Promise is a constructor and Promise is used generate Promise instance. 2. Promise is a solution in asynchronous programming.
How to create a Promise instance?
writing style 1
var promise = new Promise(function(resolve, reject) {
// ... some code
if (/* aync action successfully */){
resolve(value);
} else {
reject(error);
}
});
writing style 2
var promise = new Promise(function(resolve, reject) {
setTimeout(() => {
resolve(data);
reject(errMessage);
}, 1000).then(data => {
console.log(data);
}, err => {
console.log(err);
})
});
e.g.1
new Promise((resolve, reject) => {
// 1st time request
setTimeout(() => {
resolve() // jump to then()
}, 1000)
}).then(() => {
// 1st time to get result
console.log('resolve 001....');
return new Promise((resolve, reject) => {
// 2nd time request
setTimeout(() => {
resolve() // jump to then()
}, 1000)
})
}).then(() => {
// 2nd time to get result
console.log('resolve 002....');
return new Promise((resolve, reject) => {
// 3rd time request
setTimeout(() => {
resolve() // jump to then()
}, 1000)
})
}).then(() => {
// 3rd time to get result
console.log('resolve 003....');
})
result will be output as below:
e.g.2
new Promise((resolve, reject) => {
setTimeout(() => {
resolve("hello world")
// reject("error message")
}, 1000)
}).then((data) => {
console.log('data:----', data);
}).catch((err) => {
console.log('err:----', err);
})
output is as below:
?e.g.3
new Promise((resolve, reject) => {
setTimeout(() => {
// resolve("hello world")
reject("error message")
}, 1000)
}).then((data) => {
console.log('data:----', data);
}).catch((err) => {
console.log('err:----', err);
})
new Promise((resolve, reject) => {
setTimeout(() => {
//resolve("hello world")
reject("error message")
}, 1000)
}).then((data) => {
console.log('data:----', data);
}, err => {
console.log('err:----', err);
})
output is as below:
Promise paramete analyze
Promise style belongs to chain programming.? Parameters are also belong to function which makes it look elegant.
pending: on waiting. e.g. network request is ongoing.
fullfill: fullfilled. call back resolve() and .then()
reject: rejected. callback reject() and .catch()
|