Privacy Policy
Snippets index

  Promises with VanillaJS

.

Exercise: Return a value after a delay

Strategy:

  • the Promise is an object whose constructor accepts an executor function as its only parameter
  • that is, a function which receives two parameters resolve and reject which must be two functions (callback)
  • in the body of the executor function an asynchronous process is normally invoked by specifying a further "local" callback which will receive the result in due time
  • the callback in turn returns the result via resolve
  • the only way for the caller to receive the result is to associate a then() method with the Promise
function print(text) {
    element.textContent = text
}

function returnValueAfterDelay(value, delay) {
    let promise = new Promise(function(resolve, reject) {
        function callback() {
            resolve(value)
        }
        setTimeout(callback, delay);
    })
    return promise
}

function main() {
    returnValueAfterDelay(123, 1000).then(
        function(value) {
            print(value)
        }
    )
}

main()

or the similar version using "arrow functions" instead of "regular functions" ... (but does anyone really think it is more readable?) ...

print = (text) => {
    element.textContent = text
}

let returnValueAfterDelay = (value, delay) => {
    let promise = new Promise((resolve, reject) => {
        let callback = () => resolve(value)
        setTimeout(callback, delay)
    })
    return promise
}

let main = () => {
    returnValueAfterDelay(123, 1000).then(
        (value) => print(value)
    )
}

main()

However:

It is recommended to use regular functions when dealing with Promises, Callback functions with dynamic context, and Object methods.