V
V
Vitaly2017-02-01 13:52:43
JavaScript
Vitaly, 2017-02-01 13:52:43

How to make "reject" on timeout in async function?

Hello. Live example via promise:

const func = () => {
    return new Promise((resolve, reject)=>{
        let key = setTimeout(reject, 30000, 'Promise timeout');
        // Какие-то действия асинхронные для получения результата промиса
        removeTimeout(key);
        resolve(data);
    });
};

Now let's say we have the same situation, but the description goes through an async function
. How can we implement this in an async construct?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaliy, 2017-02-01
@vshvydky

I found it myself, I rewrite it in async style:

conf func = async function () {
  try {
    setTimeout((message)=>{
      throw new Error(message);
    } , 30000, 'Promise timeout');
    // наш асинхронный запрос с использованием await 
    return result;
  } catch (e) {
    // что-то выполняем
     return await Promise.reject(e);
    // Альтернативный вариант Дмитрия:
    throw e;
  } 
};

func().tnen(console.log).catch(console.error);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question