跳到主要内容

1 篇博文 含有标签「async」

查看所有标签

· 阅读需 1 分钟

REF: https://www.youtube.com/watch?v=zoZiQJ38bXk

Normal Promise

./hello.js
function sendRequest() {
return new Promise(function(resolve, reject){
setTimeout(function(){
resolve("Lintao")
}, 2000)
});
}

let promise = sendRequest();
promise.then(function(username) {
console.log(username)
})

Change to Await

./hello-await.js
function sendRequest() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve("Lintao");
}, 2000);
});
}


// must put await inside async function
async function getUsername() {
// put await in front of a function which returns a Promise object
console.log(await sendRequest());
}

getUsername()

Error handling

./hello-await-error-handling.js
function sendRequest() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
reject("Lintao");
}, 2000);
});
}

async function getUsername() {
// put inside try..catch block
try {
console.log(await sendRequest());
} catch (error) {
console.log(`error: ${error}`);
}
}

getUsername();

With Fetch

./hello-await-fetch.js
function sendRequest() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
reject("Lintao");
}, 2000);
});
}

async function getUsername() {
// put inside try..catch block
try {
let username = await fetch('https://jsonplaceholder.typicode.com/users')
username = await username.json()
console.log(username);
} catch (error) {
console.log(`error: ${error}`);
}
}

getUsername();

Promise.all and typescript

REF: https://blog.logrocket.com/async-await-in-typescript/