asynchronously US: [e'sɪŋkrənəslɪ] 异步方式
use it to make a promise to do something, usually asynchronously.
任务完成后,是履行承诺还是不做
Promise is a constructor function, so you need to use the new keyword to create one
两个参数
resolve 方法,履行承诺
reject 方法,拒绝
const myPromise = new Promise(function(resolve, reject){
});
const myPromise = new Promise((resolve, reject) => {//省略了function 添加了=>
});
Promise 有三个状态 states
pending 等待
fulfilled 完成
rejected 拒绝
const myPromise = new Promise((resolve, reject) => {
if(condition here) {
resolve("Promise was fulfilled");
} else {
reject("Promise was rejected");
}
}
//Promise 在任务时间未知的情况下特别有效
//promise is fulfilled with resolve,当promise 成功完成会立即调用then 方法
myPromise.then(function(result){
console.log(result);
})
myPromise.then(result => {
console.log(result);
})
//promise reject 的时候会调用catch 方法
myPromise.catch(error => {
// do something with the error.
});
//chained
myPromise
.then(result => {
console.log(result);
})
.catch(error => {
console.log(error);
});