1

Hello i'm trying to use fibers for waiting request but it gives an error

'Error: Can't wait without a fiber'

What should i do to work with that.By the way im not using meteor just pure nodejs.

const Fiber = require('fibers')
const Future = require('fibers/future')
const request = require('request')
const v3_key = "*****";

// Application Declartion
function Movie() {
    this.apiKey = v3_key;
}

/**
Now playing search on tmdb with
    page
    language
*/
Movie.now_playing = (page,language) =>{

    let now_playing = new Future()

    const options = {
        method:"GET",
        url:"https://api.themoviedb.org/3/movie/now_playing",
        qs:{
            page:page ? page : 1,
            language:language ? language : "en-US",
            apiKey:v3_key
        },
        body:'{}'
    };

    request(options,(error,response,body)=>{
        if(error) now_playing.return(error);


        now_playing.return(response);

    });

    console.log(now_playing);
    return now_playing.wait();

};


module.exports = Movie
Uğur Oruc
  • 56
  • 14

1 Answers1

1

The now_playing.wait() call needs to be executed in the "context" of a fiber. It cannot be executed in a top-level event context (e.g., from a setTimeout callback), nor in the default initial context.

The most direct way to get a context with a fiber is create a new Fiber and invoke run() on it. But there are lots of environments that create fibers for you (e.g., Meteor is probably creating the Fiber for you if you're used to using Meteor).

So, the problem isn't necessarily with this code. The caller of Movie.now_playing needs to make sure the method is invoked in a fiber context. If you've got fibers elsewhere, then make sure this is being invoked in that context, and not in a top-level event callback (e.g., fiber-unaware node modules might invoke a callback in response to an OS event -- that won't be a fiber context.) If you're rolling everything yourself, make sure you've created the first Fiber and run it to get into a Fiber context where "wait" is permissible.

Control flow with futures: Also, your request callback is a bit broken, as in the "error" case both "return" statements will execute. In general, when invoking "return" or "throw" on a future, you should probably prefix the line with return to match the control-flow semantics to the code:

request(options,(error,response,body)=>{
    if (error) return now_playing.return(error);
    return now_playing.return(response);
});
Alex Tullenhoff
  • 371
  • 4
  • 11