24
loading...
This website collects cookies to deliver better user experience
async myFunction() {
// body of the function
}
([...any]): Promise<any>
async myFirstFunction() {
// some logic
const partial = await getParialResult(); // calling another async function or function returning promise
// other logic
return processPartial(partial) // calling sync function with non promise parameter returning non promise value
}
some logic
is executed synchronously. The part other logic
is executed asynchronously only afterPromise
object.undefined
value, the async function returns Promise<undefined>
- Promise resolved to undefined
.async myFunction() {
console.log('hi from async function')
}
Promise
and not undefined
, the value is wrapped in the resolved Promise
async function myFunction() {
...
return 'hello world'
}
myFunction() // Promise { 'hello world' }
function myFunction() {
return Promise.resolve('hello world')
}
Promise.resolve
will automatically flatten any nested layers if "thenable" object is found. This is not the case of async function return. Here the value wrapped inside promise is unwrapped and wrapped again in new Promise object.const myPromise = new Promise((resolve, reject) => { resolve(42) });
async function myAsyncFunction() { return myPromise }
var p = myFunction()
// p is holding Promise { 42 }
p === myPromise // false
myPromise === Promise.resolve(myPromise) // true, because the nested structure is flattened
function mySyncFunction() { return myPromise }
var p = myFunction()
// p is holding Promise { 42 }
p === myPromise // true
function likeAsyncFunction() {
// value inside promise is unwrapped and wrapped again in new promise object
return myPromise.then(value => Promise.resolve(value))
}
p = likeAsyncFunction() // Promise { 42 }
myPromise === p // false
await
keyword could go into then
handler. Is this true?// app.js
// run node app.ja
/*
* this function will be used trhought few more examples, so keep it.
* when using plain promises the async keyword can be ignored (ref. to the above explanation)
*/
async function sleep(mls) {
return new Promise((resolve) => {
setTimeout(() => {
console.log('resolving...')
resolve(mls)
}, mls)
})
}
async function serviceB() {
console.log('serviceB:1');
await sleep(1000)
console.log('serviceB:2')
}
async function serviceA() {
console.log('serviceA:1')
await serviceB()
console.log('serviceA:2')
}
console.log('before')
serviceA();
console.log('after')
before
serviceA:1
serviceB:1
after
resolving...
serviceB:2
serviceA:2
function serviceB() {
console.log('serviceB:1');
return new Promise(resolve => {
sleep(1000).then(() => {
console.log('serviceB:2')
resolve();
})
})
}
function serviceA() {
console.log('serviceA:1')
return new Promise((resolve) => {
serviceB().then(() => {
console.log('serviceA:2')
resolve();
})
})
}
console.log('before')
serviceA();
console.log('after')
console.log('after')
.serviceA()
serviceB()
serviceC()
serviceA().then(callbackA)
serviceB().then(callbackB)
serviceC().then(callbackC)
async-await
async function update(earliestVersion, lastVersion)
{
for (i = earliestVersion; i <= lastVersion, i++) {
try {
await applyUpdate(`version_${first}`);
} catch(e) {
throw Error('Update Error')
}
}
}
// possible usage in the code:
update(12, 16)
.then(handleSuccess)
.catch(handleError)
.finally(handleFinish)
function update(earliestVersion, lastVersion) {
function _update(version){
return applyUpdate(version)
.then((res) => {
if (version <= lastVersion) {
return _update(version + 1)
} else {
return res;
}
})
.catch(() => { throw Error('Update Error') })
}
return _update(version)
}
async function reportStatus(nu) {
let status = false;
let tries = 0;
while (!status) {
await status = getTurbineStatus(nu)
logStatusCall(no, status, tries++)
}
return status;
}
// usage
turbines.forEach(reportStatus)
// or
Promses.allSettled(turbines.map(reportStatus))
.then(handleResponses)
function reportStatus(nu) {
let status = false;
let tries = 0;
function _helper(n){
return getTurbineStatus(n).then((status) => {
logStatusCall(no, status, tries++)
if (!status) {
return _helper(n);
} else {
return status
}
})
}
return _helper(nu)
}
async function* countdown(count, time) {
let index = count;
while (index) {
await sleep(time)
yield --index;
}
}
async function testCountDown(count) {
const cd = countdown(4, 1000)
let val = await cd.next();
while (!val.done) {
console.log(`finish in ${val.value}`)
val = await cd.next();
}
console.log('...finished')
}
testCountDown(5)
{ value, done }
is wrapped in the Promise.for..of
loop neither it will work with spread operator [...iterable]
.iterable
and the interpreter can't access the { value, done }
object directly.this
refers to the calling object even in the async part of the block which following after await
keyword. To refer to this
from inside the promise handler we need to use arrow functions or to bind this
.function logName() {
console.log(`Hi, my name is ${this.name}.`)
}
class Simpson {
constructor(name) {
this.name = name
}
logName() {
console.log(`Hi, my name is ${this.name}.`)
}
async waitAndSayHi(time) {
await sleep(time);
this.logName();
}
waitAndSayHiWithPromise(time) {
return new Promise(resolve => {
sleep(time).then(this.logName.bind(this))
})
}
}
const lisa = new Simpson('Lisa')
const bart = new Simpson('Bart')
lisa.waitAndSayHi(500)
bart.waitAndSayHiWithPromise(1000)
.bind(this)
will result in the obvious error for obvious reasons. Something we don't need to worry about when using async-await
.