带有setTimeout的嵌套Promise [英] Nested Promise with setTimeout

查看:561
本文介绍了带有setTimeout的嵌套Promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个嵌套的承诺.承诺基于另一个setTimeout为0的承诺解决或拒绝来解决或拒绝,以免阻塞:

I have a nested promise. The promise resolves or rejects based on another promise resolving or rejecting with a setTimeout of 0 so as not to clog:

  return new Promise((resolve, reject) => {
    promiseInst
    .then(value => {
      executeSoon(() => {
        dispatch({ ...action, status: "done", value: value });
        resolve(value);
      });
    })
    .catch(error => {
      executeSoon(() => {
        dispatch({
          ...action,
          status: "error",
          error: error.message || error
        });
        reject(error);
      });
    });
});

executeSoon()executeSoon(fn) { setTimeout(fn, 0); }

我该如何简化?试图摆脱外部promise包装器并直接返回内部promise,但是卡在解析和拒绝中,但未定义.所以我想我只是从.then内部返回Promise.resolve(value),从捕获中返回Promise.reject(error),但这也不起作用.我觉得有可能简化此过程,但不能完全绕开它.

How do I simplify this? Tried to get rid of the outer promise wrapper and returning the inner promise directly but got stuck with the resolve and reject not being defined. So I thought I'd just return a Promise.resolve(value) from inside the .then and Promise.reject(error) from the catch, but this does not work either. I feel it might be possible to simplify this, but can't quite get my head around it.

推荐答案

请记住,始终都是 执行的then处理程序,通常情况下不需要setTimeout(..., 0).因此,如果setTimeout没有其他用途:

Remember that a then handler is always executed asychronously, there's no need for setTimeout(..., 0) in the normal case. So if the setTimeout doesn't have another purpose:

return promiseInst
    .then(value => {
        dispatch({ ...action, status: "done", value: value });
        return value;
    })
    .catch(error => {
        dispatch({ ...action, status: "error", error: error.message || error });
        throw error;
    });

如果它做的很重要,那么我可能会有一个支持承诺的版本,大致如下:

If it does something important, I'd probably have a promise-enabled version, something along these lines:

const setTimeoutPromise = (delay = 0) => new Promise(resolve => {
    setTimeout(resolve, delay);
});

然后查看下面带有***的行:

Then see the lines with *** below:

return promiseInst
    .then(value => setTimeoutPromise().then(() => value) // ***
    .then(value => {
        dispatch({ ...action, status: "done", value: value });
        return value;
    })
    .catch(error => setTimeoutPromise().then(() => {     // ***
        dispatch({ ...action, status: "error", error: error.message || error });
        throw error;
    })); // <== *** Note one more )

这篇关于带有setTimeout的嵌套Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆