简体   繁体   中英

TypeError: You may only yield a function, promise, generator… when yielding app.listen()

I cannot tell what is wrong with this generator function:

var dbUrl = 'mongodb://localhost:27017/voyanta';
var db;
var server;

co(function*() {
    // Use connect method to connect to the Server
    db = yield MongoClient.connect(dbUrl);
    server = yield app.listen(3000);
    console.log('Connected to database. Listening on port 3000.');

}).catch(function(err) {
    console.log(err.stack);
});

It looks perfectly fine to me, but the line "server = yield app.listen(3000);" creates the error: "Type Error: You may only yield a function, promise, generator, array, or object, but the following object was passed: "[object Object]".

app.listen(3000) doesn't return a promise.

Instead of:

server = yield app.listen(3000);

you can do something like:

server = app.listen(3000);
yield new Promise(res => server.on('listening', res));

or better yet:

server = app.listen(3000);
yield new Promise((res, rej) => {
    server.on('listening', res);
    server.on('error', rej);
});

Tested with this example:

var co = require('co');
var app = require('express')();

co(function*() {
    server = app.listen(3000);
    yield new Promise((res, rej) => {
        server.on('listening', res);
        server.on('error', rej);
    });
    console.log('Listening on port 3000.');
}).catch(function(err) {
    console.log(err.stack);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM