-1

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

1 Answers1

0
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

  • the thing is the challenge needs to follow this specific format of answering. – Yahya Elfaqir Sep 19 '20 at 22:00
  • Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Mark Rotteveel Sep 20 '20 at 09:26
  • Updated the explanation, the exercise is to use the promise object without changing the format of the skeleton provided. – Yahya Elfaqir Sep 20 '20 at 10:47
  • @YahyaElfaqir Surely you can fill out the skeleton with the help of the code provided in this answer and the canonical question. – Bergi Sep 20 '20 at 11:12
  • @MarkRotteveel I thought that the code was clear enough but I have included the explanation now – Ahmed Abuthwabah Sep 20 '20 at 12:16