MDGSF Software Engineer

[Web] javascript async

2018-07-06
mdgsf
Web

async 函数

async function timeout() {
  return 'hello world'
}
t = timeout()
console.log(t)
t.then(result => {
  console.log(result)
})
console.log('虽然在后面,但是我先执行')

输出:

Promise { <state>: "fulfilled", <value>: "hello world" }
虽然在后面,但是我先执行
hello world

1. async 函数返回一个 Promise 对象。

2. async 函数会和正常流程并行执行。

async 函数中加入 await

function GetDataFromServer1() {
  return "server 1 data"
}

function GetDataFromServer2() {
  return "server 2 data"
}

async function ShowDataToUser() {
  data1 = await GetDataFromServer1()
  data2 = await GetDataFromServer2()
  return data1 + "\n" + data2
}

ShowDataToUser().then(result => {
  console.log(result)
})
console.log('虽然在后面,但是我先执行')

输出:

虽然在后面,但是我先执行 Scratchpad/1:27:1
server 1 data
server 2 data

weixingongzhonghao

Comments

Content