在vue中使用Promise
// 成功的回调函数
function successCallback(result) {
console.log("音频文件创建成功: " + result);
}
// 失败的回调函数
function failureCallback(error) {
console.log("音频文件创建失败: " + error);
}
// audioSettings 一些配置
createAudioFileAsync(audioSettings, successCallback, failureCallback)
-
如果函数 createAudioFileAsync() 被重写为返回 Promise 的形式,那么我们可以像下面这样简单地调用它:
const promise = createAudioFileAsync(audioSettings); promise.then(successCallback, failureCallback); // 或者简写为 createAudioFileAsync(audioSettings).then(successCallback, failureCallback);
-
原生
let promise = new Promise((resolve, reject) => { }).then( (result) => { return result } )
async await
test() {
// 捕获错误
this.test4().catch(() => {
console.log('err');
})
}
test2 () {
//函数必须返回一个Promise对象
return new Promise( (resolve, reject) => {
setTimeout(() => {
resolve(100)
}, 2000);
})
},
async test4 () {
const x = await this.test2();
console.log(x);
console.log(3);
}
Promise
-
Promise.all()
var p1 = Promise.resolve(3); var p2 = 1337; var p3 = new Promise((resolve, reject) => { setTimeout(resolve, 100, 'foo'); }); Promise.all([p1, p2, p3]).then( result => { console.log(result); // [3, 1337, "foo"] } )
-
Promise.allSettled()
当您有多个彼此不依赖的异步任务成功完成时,或者您总是想知道每个promise的结果时,通常使用它。
const promise1 = Promise.resolve(3); const promise2 = new Promise((resolve, reject) => setTimeout(reject, 100, 'foo')); const promises = [promise1, promise2]; Promise.allSettled(promises). then((results) => results.forEach((result) => console.log(result))); // > Object { status: "fulfilled", value: 3 } // > Object { status: "rejected", reason: "foo" }
-
Promise.any()
只要其中的一个 promise 成功,就返回那个已经成功的 promise 。如果可迭代对象中没有一个 promise 成功(即所有的 promises 都失败/拒绝),就返回一个失败的 promise 和AggregateError类型的实例,它是 Error 的一个子类,用于把单一的错误集合在一起
const pErr = new Promise((resolve, reject) => { reject("总是失败"); }); const pSlow = new Promise((resolve, reject) => { setTimeout(resolve, 500, "最终完成"); }); const pFast = new Promise((resolve, reject) => { setTimeout(resolve, 100, "很快完成"); }); Promise.any([pErr, pSlow, pFast]).then((value) => { console.log(value); // pFast fulfils first }) // 期望输出: "很快完成"
-
Promise.race()
Promise.race(iterable) 方法返回一个 promise,一旦迭代器中的某个promise解决或拒绝,返回的 promise就会解决或拒绝。
const promise1 = new Promise((resolve, reject) => { setTimeout(resolve, 500, 'one'); }); const promise2 = new Promise((resolve, reject) => { setTimeout(resolve, 100, 'two'); }); Promise.race([promise1, promise2]).then((value) => { console.log(value); // Both resolve, but promise2 is faster }); // expected output: "two"
-
Promise.reject(reason)
-
Promise.resolve(value)