如何从函数中多次产生价值? [英] How to yield value multiple times from function?

查看:42
本文介绍了如何从函数中多次产生价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在做的是,我有 2 个文件,一个包含生成令牌的脚本,第二个文件处理该令牌.

So what I am doing is, I have 2 files, One that contain a script which would generate a token and the second file handle that token.

问题是记录令牌的第二个脚本只会记录收到的第一个令牌.

The problem is that the second script which would log the token it would only log the first token received.

这是我处理令牌的方式:

This is the how I am handling the token:

const first_file = require("./first_file.js");
first_file.first_file().then((res) => {
    console.log(res);
});

显然这行不通,因为它没有使用更新的值进行更新.

And clearly that wouldn't work, Because it's not getting updated with the newer value.

first_file = async () => {
    return new Promise(async (resolve, reject) => {
        //Generating the token
        (async () => {
            while (true) {
                console.log("Resolving...");
                resolve(token);
                await sleep(5000);
                resolved_token = token;
            }
        })();
    });
};

module.exports = { first_file };

我在这里做的是,我尝试执行一个 while..loop 以便我继续解析令牌.但它没有,有没有办法直接导出变量,这样任务会更容易?

What I am doing here is, I tried to do a while..loop so that I keep resolving the token. But it didn't, Is there and way I can export the variable directly so the task would be easier ?

推荐答案

如果我正确理解你的问题,你想多次解决 promise,而这与模块无关...

If I understand your question correctly, You want to resolve promise multiple times, And It's nothing to do with modules...

但是你对 JavaScript 中的 promise 理解有误...
你不能两次解决一个承诺.

But You understand something wrong about promise in JavaScript...
You can't resolve a promise twice.

但是您可以从函数中生成新值,这种类型的函数也称为 generator,其中一个函数可以重新进入其上下文(类似于 async/await)并使用 yield 关键字产生结果.

But you can generate new value from function, this type of function also known as generator, Where a function can reenter its context (Something like async/await) and yield result using yield keyword.

通常在 for..of 循环中使用生成器.它有 next() 方法用于从生成器中产生下一个值...

Usually a generator is used in for..of loop. It has next() method for yield next value from a generator...

举个例子:

const delay = ms => new Promise(res => setTimeout(res.bind(null, ms), ms));

async function* generator() {
    yield 'yield result from generator!'
    for (let ms = 100; ms <= 300; ms += 100) {
        yield 'delay: ' + await delay(ms) + ' ms';
    }
    yield delay(1000).then(() => 'you can also yield promise!');
}

async function main() {
    const gen = generator();
    console.log('1st', (await gen.next()).value);
    for await (const ms of gen) {
        console.log(ms)
    }
}

main()

注意*在函数之后,这样我们就知道这个函数是一个生成器,带有async关键字这是异步生成器.

Note that * after function, So that we know that this function a generator, with async keyword this is Async Generator.

生成器非常有用.如:按需生成值,像管道一样传递数据!,可以从函数中返回无穷无尽的值等...

Generator is very useful. like: Generate value on demand, Pass data like pipe!, Can return endless value from function etc...

这种在 node 中大量使用的老派方法,您将回调函数作为参数传递.

This old school method heavily used in node, Where you pass a callback function as argument.

示例:

const delay = ms => new Promise(res => setTimeout(res.bind(null, ms), ms));

async function callback(fn) {
    fn('yield result from callback!');
    for (let ms = 100; ms <= 300; ms += 100) {
        fn('delay: ' + await delay(ms) + ' ms');
    }
    await delay(1000);
    fn('yield asynchronously!');
}

callback(value => console.log(value));

这种方法会产生各种棘手的问题,例如:创建的函数作用域、控制流的灾难、没有 break 关键字等...我不推荐这种方法.

This approach create all sort of nutsy problem, like: created function scope, disaster of control flow, doesn't have break keyword etc... I don't recommend this method.

这篇关于如何从函数中多次产生价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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