Does node.js support yield?

后端 未结 10 665
误落风尘
误落风尘 2021-01-31 01:51

Is there any way to get generators into node.js?

I\'m currently faking them with callbacks, but I have to remember to check the response of the callback inside of my gen

10条回答
  •  伪装坚强ぢ
    2021-01-31 02:34

    Apparently not in the current stable version. You can however achieve the same using node-fibers + promises.

    Here is my implementation:

    var fiber = require('fibers');
    
    module.exports.yield = function (promise) {
    
        var currentFiber = fiber.current;
        promise
            .then(function (value) {
                currentFiber.run(value);
            })
            .otherwise(function (reason) {
                currentFiber.throwInto(reason);
            });
    
        return fiber.yield();
    };
    module.exports.spawn = function (makeGenerator) {
        fiber(function () {
            makeGenerator.apply(this, Array.prototype.slice.call(arguments, 1));
        }).run();
    };
    

    And a sample code on how it works: (query.find returns a promise)

            var generators = require('./utils/generators');
            var query = require('./utils/query');
    
            generators.spawn(function () {
                try {
                    var field1 = generators.yield(query.find('user', { _id : '1' }));
                    var field2 = generators.yield(query.find('user', { _id : '2' }));
                    console.log('success', field1[0]._id, field2[0]._id);
                }
                catch (e) {
                    console.error('error', e);
                }
            });
    

提交回复
热议问题