合并异步操作,promise.then() 和递归 setTimeout,同时避免 "deferred antipattern"

Incorporating async actions, promise.then() and recursive setTimeout whilst avoiding "deferred antipattern"

我一直在阅读实现轮询功能的方法,并在 https://davidwalsh.name/javascript-polling 上找到了一篇很棒的文章。现在使用 setTimeout 而不是 setInterval 来轮询日志是有意义的,尤其是对于我无法控制的 API 并且已显示具有不同的响应时间。

所以我尝试在自己的代码中实现这样的解决方案,以挑战我对回调、承诺和事件循环的理解。我已遵循 post 中概述的指导以避免任何反模式 and to ensure promise resolution before a .then() ,这就是我遇到困难的地方。我已经将一些代码放在一起来模拟场景,这样我就可以突出问题。

我假设的场景是这样的: 我对服务器进行了 API 调用,该服务器使用用户 ID 进行响应。然后我使用该用户 ID 向另一个数据库服务器发出请求,该服务器 returns 一组数据,执行一些可能需要几分钟的机器学习处理。

由于延迟,任务被放入任务队列,一旦完成,它就会更新 NoSql 数据库条目,从 isComplete: falseisComplete: true。这意味着我们需要每隔 n 秒轮询一次数据库,直到我们收到指示 isComplete: true 的响应,然后我们停止轮询。我知道轮询 api 有很多解决方案,但我还没有看到涉及承诺、条件轮询和不遵循先前链接 post 中提到的一些反模式的解决方案。如果我错过了什么,这是重复的,我提前道歉。

到目前为止,该过程由以下代码概述:

let state = false;
const userIdApi = ()  => {
    return new Promise((res, rej) => {
  console.log("userIdApi");
  const userId = "uid123";
      setTimeout(()=> res(userId), 2000)
    })
}

const startProcessingTaskApi = userIdApi().then(result => {
    return new Promise((res, rej) => {
    console.log("startProcessingTaskApi");
        const msg = "Task submitted";
      setTimeout(()=> res(msg), 2000)
    })
})

const pollDatabase = (userId) => {
    return new Promise((res, rej) => {
  console.log("Polling databse with " + userId)
      setTimeout(()=> res(true), 2000)
    })
}


Promise.all([userIdApi(), startProcessingTaskApi])
    .then(([resultsuserIdApi, resultsStartProcessingTaskApi]) => {
      const id = setTimeout(function poll(resultsuserIdApi){
        console.log(resultsuserIdApi)
        return pollDatabase(resultsuserIdApi)
        .then(res=> {
            state = res
            if (state === true){
              clearTimeout(id);
              return;
              }
            setTimeout(poll, 2000, resultsuserIdApi);
            })
            },2000)
        })

我有一个与此代码相关的问题,因为它未能按我的需要执行轮询:

我在 post 的已接受答案中看到,应该 "Break the chain" 避免大量的 .then() 语句链。我遵循了指导,它似乎可以解决问题(在添加轮询之前),但是,当我在控制台注销每一行时,似乎 userIdApi 被执行了两次;一次在 startProcessingTaskApi 定义中使用,然后在 Promise.all 行中使用。

这是已知事件吗?它发生的原因是有道理的 我只是想知道为什么发送两个请求来执行相同的承诺是好的,或者是否有办法可能阻止第一个请求发生并将函数执行限制在 Promise.all声明?

我是 Javascript 的新手,来自 Python,所以任何关于我可能遗漏一些知识以能够使这个看似简单的任务正常工作的指示都将不胜感激。

我想你快到了,看来你只是在与 javascript 的异步性质作斗争。使用 promises 绝对是到达这里的方式,理解如何将它们链接在一起是实现您的用例的关键。

我将从实现一个包装 setTimeout 的单一方法开始,以简化事情。

function delay(millis) {
    return new Promise((resolve) => setTimeout(resolve, millis));
}

然后您可以使用 delay 函数重新实现 "API" 方法。

const userIdApi = () => {
    return delay(2000).then(() => "uid123");
};

// Make userId an argument to this method (like pollDatabase) so we don't need to get it twice.
const startProcessingTaskApi = (userId) => {
    return delay(2000).then(() => "Task submitted");
};

const pollDatabase = (userId) => {
    return delay(2000).then(() => true);
};

当您的条件不满足时,您可以通过简单地在链中链接另一个承诺来继续轮询数据库。

function pollUntilComplete(userId) {
    return pollDatabase(userId).then((result) => {
        if (!result) {
            // Result is not ready yet, chain another database polling promise.
            return pollUntilComplete(userId);
        }
    });
}

然后您可以将所有内容放在一起来实现您的用例。

userIdApi().then((userId) => {
    // Add task processing to the promise chain.
    return startProcessingTaskApi(userId).then(() => {
        // Add database polling to the promise chain.
        return pollUntilComplete(userId);
    });
}).then(() => {
    // Everything is done at this point.
    console.log('done');
}).catch((err) => {
    // An error occurred at some point in the promise chain.
    console.error(err);
});

如果您能够实际使用 asyncawait 关键字,这将变得 很多 容易。

使用与 Jake 的回答相同的 delay 函数:

async function doItAll(userID) {
    await startTaskProcessingApi(userID);
    while (true) {
        if (await pollDatabase(userID)) break;
    }
}