有没有一种方法可以将回调函数转换为TypeScript / JavaScript中的生成器?

时间:2019-10-27 10:42:04

标签: javascript typescript callback axios generator

我正在使用Axios调用具有进度指示器的api端点。我想将onUploadProgress转换为生成器。

有没有办法转换此代码

setProgress({ state: 'syncing', progress: 0 });

await axios.post(uri.serialize(parsedURI), body2, {
    headers: { session_id: sessionId },
    onUploadProgress: (progress) => {
        setProgress({ state: 'syncing', progress: progress.loaded / progress.total });
    },
});
setProgress({ state: 'syncing', progress: 1 });

变成这样

yield { state: 'syncing', progress: 0 };

await axios.post(uri.serialize(parsedURI), body2, {
    headers: { session_id: sessionId },
    onUploadProgress: (progress) => {
        yield { state: 'syncing', progress: progress.loaded / progress.total };
    },
});
yield { state: 'syncing', progress: 1 };

问题出在onUploadProgress内部的yield上,我在想可能有一种使用它的方法,例如当您要将回调转换为您使用的promise时

new Promise(resolve => fn(resolve));

也许对于像这样的发电机有一些有效的方法

new Generator(next => fn(next));

2 个答案:

答案 0 :(得分:2)

您可以在进度处理程序中更新局部变量,并在循环中对其进行轮询,直到请求完成为止。这是草图:

let delay = n => new Promise(res => setTimeout(res, n));


async function request(n, onProgress) {
    for (let i = 0; i < n; i++) {
        onProgress(i);
        await delay(200);
    }
    return 'response'
}


async function* requestWithProgress(result) {
    let prog = 0,
        prevProg = 0,
        res = null;

    let req = request(10, n => prog = n)
        .then(r => res = r);

    while (!res) {
        await delay(1);
        if (prog > prevProg)
            yield prevProg = prog;
    }

    result.res = res;
}


async function main() {
    let result = {}
    for await (let prog of requestWithProgress(result))
        console.log(prog)
    console.log(result)
}


main()

这是另一个选项,无需轮询,并且返回API更好:

function progressiveAsync(factory) {
    let
        resultPromise = null,
        resultResolver = null,
        genPromise = null,
        genResolver = null,
        stop = {};

    resultPromise = new Promise(r => resultResolver = r);
    genPromise = new Promise(r => genResolver = r);

    async function* gen() {
        while (true) {
            let r = await genPromise;
            if (r === stop) {
                break;
            }
            yield r;
        }
    }

    factory(
        val => {
            genResolver(val);
            genPromise = new Promise(r => genResolver = r);
        },
        val => {
            genResolver(stop);
            resultResolver(val);
        }
    );

    return [gen(), resultPromise];
}

//


async function testRequest(opts /* count, onProgress */) {
    return new Promise(async res => {
        for (let i = 0; i < opts.count; i++) {
            opts.onProgress(i);
            await new Promise(resolve => setTimeout(resolve, 300));
        }
        res('response!')
    })
}


async function main() {
    let [progress, result] = progressiveAsync((next, done) =>
        testRequest({
            count: 10,
            onProgress: next
        }).then(done));

    for await (let n of progress)
        console.log('progress', n)

    console.log(await result)
}

main()

答案 1 :(得分:-1)

我更改了一些@georg代码,以允许将此方法与任何功能一起使用,并具有更接近要求的界面

async function* createGenerator<T>(factory: (
    next: (value: T) => void, 
    complete: () => void) => void,
): AsyncIterableIterator<T> {
    let completed = false;
    let value: { value: T } | null = null;

    factory(
        (v: T) => {
            value = { value: v };
        }, 
        () => {
            completed = true;
        },
    );

    while (!completed) {
        if (value != null) {
            yield (value as { value: T }).value;
            value = null;
        }
        value = null;
        await new Promise(resolve => setImmediate(resolve));
    }
}

所以现在可以像这样使用

yield { state: 'syncing', progress: 0 };

yield* createGenerator<Progress>((next, complete) => {
    axios.post(uri.serialize(parsedURI), body, {
        headers: { session_id: sessionId },
        onUploadProgress: (progress) => {
            next({ state: 'syncing', progress: progress.loaded / progress.total });
        },
    }).then(() => complete());
});

yield { state: 'syncing', progress: 1 };