async function getStockPriceByName(name) {
const symbol = await getStockSymbol(name);
const stockPrice = await getStockPrice(symbol);
return stockPrice;
}
getStockPriceByName('goog').then(function (result) {
console.log(result);
});
async function f() {
return 'hello world';
}
f().then(v => console.log(v))
// "hello world"
async function f() {
// 等同于
// return 123;
return await 123;
}
f().then(v => console.log(v))
// 123
async function dbFuc(db) {
let docs = [{}, {}, {}];
// 报错
docs.forEach(function (doc) {
await db.post(doc);
});
}
async function dbFuc(db) {
let docs = [{}, {}, {}];
for (let doc of docs) {
await db.post(doc);
}
}
// 或者下面的写法
async function dbFuc(db) {
let docs = [{}, {}, {}]
let promises = docs.map((doc) => db.post(doc))
let results = []
for (let promise of promises) {
results.push(await promise)
}
console.log(results)
}
// 或者下面的写法
async function dbFun(db) {
let docs = [{}, {}, {}]
let promises = docs.map((doc) => db.post(doc))
let results = await Promise.all(promises)
console.log(results)
}
async function logInOrder(urls) {
// 并发读取远程URL
const textPromises = urls.map(async url => {
const response = await fetch(url)
return respone.text()
})
// 按次序输出
for (const textPromise of textPromises){
console.log(await textPromise)
}
}