1. new primise
new Promise(function (resolve, reject) {
console.log(1111);
resolve(2222);
}).then(function (value) {
console.log(value);
return 3333;
}).then(function (value) {
console.log(value);
throw "An error";
}).catch(function (err) {
console.log(err);
});
执行结果:
2. return new promise
function print(delay, message) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
console.log(message);
resolve();
}, delay);
});
}
print(1000, "First").then(function () {
return print(4000, "Second"); //若不要return又是不一样的结果
}).then(function () {
print(3000, "Third");
});
执行结果:
3. async await配合promise vue中使用
mounted() {
this.getAll()
this.get()
},
methods: {
async getAll() {
await this.print(400, '111')
await this.print(400, '222')
await this.print(400, '333')
},
async get() {
// 同步执行
let res = await this.print(400, '444') // 先执行
console.log(res + 'a') //再执行,
},
print(delay, message) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
console.log(message);
resolve(123);
}, delay);
});
}
}
4.await 指令后必须跟着一个 Promise
async function asyncFunc() {
try {
await new Promise(function (resolve, reject) {
throw "Some error"; // 或者 reject("Some error")
});
} catch (err) {
console.log(err);
// 会输出 Some error
}
}
asyncFunc();
async function asyncFunc() {
let value = await new Promise(
function (resolve, reject) {
resolve("Return value");
}
);
console.log(value); //会输出 Return value
}
asyncFunc();
5.
async chongGuo() {
let res = await new Promise((resolve, reject)=>{ // 同步
console.log(1);
resolve('99')
})
let res1 = res
console.log(res1);
console.log(2);
}
执行顺序