0

Say I have a function which returns the result on an input after 1 sec:

function slowDouble(num) {
    setTimeout(() => {
        return num * 2;
    }, 1000);
}

Now I want to call this function and wait until the result is returned, so I can do other operations on it. I tried to wrap this function in a Promise but the result is returned to then block after the log statement is executed (printing undefined):

function promisify(num) {
    return new Promise((resolve) => {
        var res = slowDouble(num);
        resolve(res);
    });
}

function promisifyTest(num) {
    promisify(num).then((res) => {
        console.log('then result ', res);
    })
}

promisifyTest(4); // undefined

Then I tried to use await:

async function asyncCallToAPI(num) {
    var tt = await promisify(num);
    console.log('async result', tt);
}

asyncCallToAPI(3); // undefined

and got the same undefined result back. I know this is very similar to other questions asked here but I couldn't figure this out yet.

3
  • Possible duplicate of stackoverflow.com/questions/39495551/… Commented Oct 3, 2018 at 19:30
  • @estus My question is actually about handling the delay not making the delay. Commented Oct 3, 2018 at 19:32
  • I see. The problem is that slowDouble is originally wrong. You can't return anything from setTimeout callback. slowDouble should initially use promises or callbacks in some other way. Commented Oct 3, 2018 at 19:35

1 Answer 1

2

You're not properly wrapping the setTimeout into a promise. Your slowDouble doesn't return anything. That's why you get undefined. You need to change how you wrote this so that the slowDouble function returns a promise, and you can get rid of the promisify function.

The difference is when you're constructing a promise, you need to be able to call the resolve callback from within the callback for whatever asynchronous function you're trying to wrap. In the case of setTimeout, we need to call resolve from within the callback to setTimeout.

function slowDouble(num) {
  return new Promise(resolve => {
    setTimeout(() => resolve(num * 2), 1000);
  });
}

async function promisifyTest(num) {
  const result = await slowDouble(num);
  console.log('Async result:', result);
}

console.log('Waiting...');
promisifyTest(4);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.