-
Hi, I've been working on a directive lately and ran in to a problem in evaluating promises. It seems that the eg. <!DOCTYPE html>
<html lang="en">
<body x-data>
<div x-promise></div>
<script>
let Prom = (Alpine) => {
Alpine.directive('promise', (el, {}, {evaluate}) => {
let undefined_promise = evaluate("new Promise(()=>{console.log('running')})")
console.log( "undefined_promise",undefined_promise)
// running
// undefined_promise undefined
let wrapped_promise = evaluate("[new Promise(()=>{console.log('running')})]")
console.log( "wrapped_promise", wrapped_promise)
// running
// wrapped_promise [Promise]
let undefined_function_promise = evaluate(() => new Promise(()=>{console.log('running')}) )
console.log( "undefined_function_promise", undefined_function_promise)
// running
// undefined_function_promise undefined
let wrapped_function_promise = evaluate(() => [new Promise(()=>{console.log('running')})])
console.log( "wrapped_function_promise", wrapped_function_promise)
// running
// wrapped_function_promise [Promise]
})
}
document.addEventListener('alpine:init', () => {
Prom(Alpine)
})
</script>
<script src="https://unpkg.com/alpinejs" defer></script>
</body>
</html> Not sure if it is expected behavior or not. But it would be nice not having to resort to eval. I assume it might have something to do with https://github.com/alpinejs/alpine/blob/main/packages/alpinejs/src/evaluator.js#L137 |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
This issue has been converted to a discussion as we are now using discussions to track bugs and ideas. |
Beta Was this translation helpful? Give feedback.
-
It's expected. Alpine tries to magically resolve functions and promises to remove complexity from the page. It was a design choice of the author which unfortunately won't fit your use case. <div x-data x-promise></div>
<script>
let Prom = (Alpine) => {
Alpine.directive('promise', (el, {}, {evaluate}) => {
let foo = Alpine.dontAutoEvaluateFunctions(() => evaluate("() => new Promise(()=>{console.log('running')})"))()
console.log(foo)
})
}
document.addEventListener('alpine:init', () => {
Prom(Alpine)
})
</script>
<script src="https://unpkg.com/alpinejs" defer></script> In theory, Alpine could have a Alpine.dontAutoResolvePromises kind of thing but it would probably take a while before the PR makes it into the core. |
Beta Was this translation helpful? Give feedback.
It's expected. Alpine tries to magically resolve functions and promises to remove complexity from the page. It was a design choice of the author which unfortunately won't fit your use case.
You can work around it with by wrapping the promise in a function and asking Alpine not to auto evaluate it.