Search code examples
javascriptclosuresjavascript-objectses6-promise

Promise after delay


I have this problem that I cannot seem to know how to tackle? Write a function, promised, that takes in a value. This function will return a promise that will resolve after 2 seconds. The following code should not be edited and should use the promise object.

 function promised (val) {
     
    }
    
    // UNCOMMENT THESE TO TEST YOUR WORK!
     const createPromise = promised('wait for it...');
     createPromise.then((val) => console.log(val)); 
    // will log "wait for it..." to the console after 2 seconds

Solution

  • const sleep = async (time) => {
        return new Promise(resolve => setTimeout(resolve, time * 1000))
    }
    
    
    
    const sayHello = async () => {
        await sleep(2)
        console.log('Hello there')
    }
    
    
    sayHello()
    

    Here is the explanation:

    Use The setTimeout() which is a builtin method that calls a function or evaluates an expression after a specified number of milliseconds. setTimeout() takes 2 parameters the first one is a call back function and the second one is the number of the milliseconds. 1 second = 1000ms so 2 seconds = 2000ms and so on

    function promised (val) {
        // Create a new promise and resolve val after 2 seconds
        return new Promise(resolve => setTimeout(() => resolve(val), 2000)) //2000ms => 2 seconds
    }
    
    
    
    const createPromise = promised('wait for it...') // Pass in your message to promised function
    
    createPromise
        .then(val => console.log(val))
        // Catch errors if any you don't need it here since we are always resolving the promise i just included it here so you know it's exist 
        .catch(err => console.log(err)) 
    

    you should always use .catch unless you are 100% sure that the promise will always resolve

    example:

    function greeting(name) {
    
        return new Promise((resolve, reject) => setTimeout(() => {
            
            try {
                
                if (name.length <= 2) {
                    throw new Error('Name must be more than two characters')
                }
    
            } catch (msg) {
                reject(msg)
            } 
    
            resolve(`Hello ${name}`)
            
            
        }, 2000))
    }
    
    
    greeting('ab')
        .then(res => console.log(res))
        .catch(err => console.log(err)) // Error: Name must be more than two characters
    
    greeting('John')
        .then(res => console.log(res)) // Hello John
        .catch(err => console.log(err))
    

    Using async, await:

    const greetSomeone = async (name) => {
    
        try {
    
            // Note that you can't use await outside an async function
            const msg = await greeting(name) 
            console.log(msg)
    
        } catch (err) {
            console.log(err)
        }
    }
    
    
    
    greetSomeone('ac') // Error: Name must be more than two characters
    
    greetSomeone('Michael') // Hello Michael
    

    Learn more about Promises https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise