async function getTrace () {
pageContent = await fetch('www.google.com', {
method: 'get'
})
return pageContent
}
getTrace()
.then((data) => {
console.log('----')
console.log(data)
})
function timeout(ms) {
return new Promise(resolve => setTimeout(() => {
resolve();
console.log(111)
}, ms));
}
async function sleep() {
await timeout(3000);
console.log(123)
}
Async 後的 function 也會變promise 化
function timeout(ms) {
return new Promise(resolve => setTimeout(() => {
resolve();
}, ms));
}
async function sleep() {
await timeout(3000);
console.log(123)
}
await sleep()
console.log('end')
Async function內的return等同於resolve
function timeout(ms) {
return new Promise(resolve => setTimeout(() => {
resolve();
}, ms));
}
async function sleep() {
await timeout(3000);
console.log(123)
return 'sleep'
}
const c = await sleep()
console.log(c)
const arr = [1, 2, 3];
const asyncRes = await Promise.all(arr.map(async (i) => {
await sleep(10);
return i + 1;
}));
console.log(asyncRes);
async function asyncForEach(array, callback) {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array);
}
}
asyncForEach(arr, doSomething)