Skip to content

Instantly share code, notes, and snippets.

@jmartin-sul
Created July 9, 2019 22:53
Show Gist options
  • Save jmartin-sul/7ff93dc0b8958088b35968ae8ec54415 to your computer and use it in GitHub Desktop.
Save jmartin-sul/7ff93dc0b8958088b35968ae8ec54415 to your computer and use it in GitHub Desktop.
more test code to illustrate Promise, await, and async
timeout = 5000
promiseKeeper = (id) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(`${id} resolved at ${new Date()}`)
}, timeout);
})
}
promiseBreaker = (id) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error(`${id} rejected at ${new Date()}`))
}, timeout);
})
}
returnsAwaitResultDirectly = async () => {
console.log(await promiseKeeper('A'))
resultB = await promiseKeeper('B')
console.log(resultB)
console.log(`result B is a ${typeof resultB}`)
console.log(await promiseKeeper('C'))
console.log(`returnsAwaitResultDirectly about to await and return at ${new Date()}`)
return await promiseKeeper('D')
}
returnsAwaitResult = async () => {
console.log(await promiseKeeper('A'))
resultB = await promiseKeeper('B')
console.log(resultB)
console.log(`result B is a ${typeof resultB}`)
console.log(await promiseKeeper('C'))
resultD = await promiseKeeper('D')
console.log(`returnsAwaitResult about to return at ${new Date()}`)
return resultD
}
noReturnValue = async () => {
console.log(await promiseKeeper('A'))
resultB = await promiseKeeper('B')
console.log(resultB)
console.log(`result B is a ${typeof resultB}`)
console.log(await promiseKeeper('C'))
console.log(await promiseKeeper('D'))
console.log(`noReturnValue about to exit at ${new Date()}`)
}
// returnsAwaitResultDirectlyResult = returnsAwaitResultDirectly()
// returnsAwaitResultResult = returnsAwaitResult()
// noReturnValueResult = noReturnValue()
waitWaitWait = async () => {
console.log(`### ${new Date()}: about to await returnsAwaitResultDirectly`)
console.log(await returnsAwaitResultDirectly())
console.log(`### ${new Date()}: about to await returnsAwaitResult`)
console.log(await returnsAwaitResult())
console.log(`### ${new Date()}: about to await noReturnValue`)
console.log(await noReturnValue())
console.log(`### ${new Date()}: about to exit waitWaitWait`)
}
// look at waitResult intermittently while waitWaitWait is running. should see that it
// is a Promise, and that it doesn't resolve till after the body of waitWaitWait completes
waitResult = waitWaitWait()
shouldErrorEarly = async () => {
await promiseBreaker('X')
console.log(`made it past rejected awaited promise ${new Date()}`)
return 'ok'
}
shouldErrorEarlyResult = shouldErrorEarly()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment