0

While running the following (simplified) code in meteor, I encountered an unexpected behaviour:

import { HTTP } from 'meteor/http';
Fiber = Npm.require('fibers');

let x = {};

Fiber(function() {
    x.a = 1;

    let result = HTTP.get('https://jsonplaceholder.typicode.com/posts/1');

    x.a = 2;
    console.log('fiber finished!');
}).run();

console.log(x);

Output:

{ a: 1 }
fiber finished!

HTTP.get is (supposed to be) synchronous according to it's documentation. I tried using another library instead of meteor/http but got the same result.

It seems like the execution within the fiber stops when it reaches the HTTP request and continues outside the fiber. Only after it finishes outside the fiber, it returns to finish up what it started within the fiber.

What's going on? How can I make an HTTP request within a fiber without this context switch?

Yarin
  • 141
  • 6
  • Take a look at [this](https://github.com/laverdet/node-fibers#sleep). It appears that while there is a blocking request inside of the fiber the rest of the code will continue execution. – forrestmid Aug 31 '17 at 18:32
  • @forrestmid, This confirms my suspicions, thank you. Now the question is, how do I prevent this behaviour from within the function I pass to Fiber().run()? – Yarin Sep 01 '17 at 19:10
  • I don't think you can prevent it, but you can work around it. If you place all your code after the `Fiber` function within its own function, then you can call the function at the end of the `Fiber` function. For example, `let x={};var fn=function(){console.log(x);};Fiber(function(){x.a=1;let result = HTTP Request;x.a = 2; console.log('fiber finished!');fn();})` – forrestmid Sep 01 '17 at 19:16

0 Answers0