new Promise(function(resolve, reject){
setTimeout(() => {
console.log("first");
resolve();
}, 1000);
}).then(function(){
return new Promise(function(resolve, reject){
setTimeout(() => {
console.log("second");
resolve();
}, 4000);
})
}).then(function(){
setTimeout(() => {
console.log("third");
}, 3000);
})
简化
//-----------------简化---------------------------------
function print(delay, message){
return new Promise(function(resolve, reject){
setTimeout(() => {
console.log(message);
resolve();
}, delay);
})
}
print(1000, 'first').then(function(){
return print(2000, 'second');
}).then(function(){
print(0, 'third');
throw "an error";
}).catch(function(error){
console.log(error);
})
//----------------------async/await----------------
async function asyncFunc(){
await print(1000, 'first');
await print(2000, 'second');
await print(1000, 'third');
}
asyncFunc();
//-------------------async/await/catch-----------------------
async function asyncFunc() {
try {
let res = await new Promise(function (resolve, reject) {
resolve("2222");
// throw "Some error"; // 或者 reject("Some error")
});
console.log(res);
} catch (err) {
console.log(err);
// 会输出 Some error
}
}
asyncFunc();
//----------------Promise.all()--------------------------
let promises = [2,3,4,5,6].map(function(id){
return "/post/"+id+".json";
})
Promise.all(promises).then(function(posts){
console.log(posts);
}).catch(function(error){
console.log(error);
})
//-------------------Promise.resolve()-----------------------
var p = Promise.resolve('hihihi');
p.then(function(s){
console.log(s);
})
//-------------------Promise.reject()-----------------------
var p = Promise.reject('出错了.');
p.then(null, function(s){
// console.log(s);
})
|