JavaScript 異步函數的創新用法有很多,以下是一些常見的用法:
function asyncOperation1() {
return new Promise((resolve, reject) => {
// 異步操作
resolve('result1');
});
}
function asyncOperation2(param) {
return new Promise((resolve, reject) => {
// 異步操作
resolve(`result2 with ${param}`);
});
}
asyncOperation1()
.then(result1 => {
console.log(result1);
return asyncOperation2(result1);
})
.then(result2 => {
console.log(result2);
})
.catch(error => {
console.error(error);
});
async function asyncOperation1() {
// 異步操作
return 'result1';
}
async function asyncOperation2(param) {
// 異步操作
return `result2 with ${param}`;
}
(async function() {
try {
const result1 = await asyncOperation1();
console.log(result1);
const result2 = await asyncOperation2(result1);
console.log(result2);
} catch (error) {
console.error(error);
}
})();
const promise1 = new Promise((resolve, reject) => {
setTimeout(() => resolve('one'), 100);
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(() => resolve('two'), 200);
});
Promise.all([promise1, promise2]).then(values => {
console.log(values); // ['one', 'two']
});
Promise.race([promise1, promise2]).then(value => {
console.log(value); // 'one'
});
async function asyncIterable() {
for (let i = 0; i < 3; i++) {
await new Promise(resolve => setTimeout(resolve, 1000));
yield `result${i}`;
}
}
(async function() {
for await (const result of asyncIterable()) {
console.log(result); // 'result0', 'result1', 'result2'
}
})();