相关疑难解决方法(0)

异步/等待超时

我使用的是Node.js和TypeScript,我正在使用它async/await.这是我的测试用例:

async function doSomethingInSeries() {
    const res1 = await callApi();
    const res2 = await persistInDB(res1);
    const res3 = await doHeavyComputation(res1);
    return 'simle';
}
Run Code Online (Sandbox Code Playgroud)

我想为整个功能设置超时.即如果res1需要2秒,res2需要0.5秒,res3需要5秒我想要超时,3秒后让我抛出错误.

正常setTimeout调用是一个问题,因为范围丢失:

async function doSomethingInSeries() {
    const timerId = setTimeout(function() {
        throw new Error('timeout');
    });

    const res1 = await callApi();
    const res2 = await persistInDB(res1);
    const res3 = await doHeavyComputation(res1);

    clearTimeout(timerId);

    return 'simle';
}
Run Code Online (Sandbox Code Playgroud)

我无法正常地抓住它Promise.catch:

doSomethingInSeries().catch(function(err) {
    // errors in res1, res2, res3 will be …
Run Code Online (Sandbox Code Playgroud)

timeout node.js promise async-await typescript

21
推荐指数
2
解决办法
2万
查看次数

基于承诺的功能的记忆

如何记忆基于承诺的功能?

直截了当的功能记忆就够了吗?

function foo() {
    return new Promise((resolve, reject) => {
      doSomethingAsync({ success: resolve, fail: reject });
    });
};
Run Code Online (Sandbox Code Playgroud)

这样就够了吗?

var fooMemoized = memoize(foo);
Run Code Online (Sandbox Code Playgroud)

注意:此问题已更新,以删除延迟反模式.

javascript memoization promise

7
推荐指数
2
解决办法
5203
查看次数

为什么 Promise.race 完成后 Node.js 不退出?

在 Node.js 中,我使用Promise.race超时和取消 Request-Promise 库发出的请求。我的Promise.race实现似乎阻止了该程序。

Promise.race确实解析并返回,但此后程序永远不会退出。

再次,我想强调等待确实完成并记录响应,但程序永远不会退出。

const rp = require('request-promise');

/**
 * @param {rp.RequestPromise} request 
 * @param {Number} ms 
 * @returns {Error}
 */
const delay = (request, ms) => new Promise((resolve, reject) => setTimeout(() => {
    request.cancel();
    return reject(new Error("Timeout"))
}, ms))

async function main() {
    try {
        const options = {
            method: 'GET',
            url: "https://api.ipify.org/?format=json",
        };

        const request = rp(options);
        const response = await Promise.race([request, delay(request, 500000)]);

        console.log(response)

    } catch (e) {
        console.log(e) …
Run Code Online (Sandbox Code Playgroud)

javascript node.js

1
推荐指数
1
解决办法
1328
查看次数