Skip to content

Instantly share code, notes, and snippets.

@yeukhon
Forked from jsantell/task-in-sdk.js
Last active August 29, 2015 14:01
Show Gist options
  • Save yeukhon/1f47a00fd1253e029356 to your computer and use it in GitHub Desktop.
Save yeukhon/1f47a00fd1253e029356 to your computer and use it in GitHub Desktop.
const { Task } = Cu.import("resource://gre/modules/Task.jsm", {});
const { defer, all } = require("sdk/core/promise");
const { setTimeout } = require("sdk/timers");
Task.spawn(function * () {
let item1 = yield getItem(1);
let [item2, item3] = all([getItem(2), getItem(3)]);
console.log(item1, item2, item3); // 1, 2, 3
}).then(function () {
console.log('all items processed')
});
function getItem(val) {
let {
deferred, resolve
} = defer();
setTimeout(() => resolve(val));
return deferred;
}
@yeukhon
Copy link
Author

yeukhon commented May 14, 2014

The code above will print undefined but in the correct blocking order (we want the task block until all values returned).

"before" main.js:7
undefined undefined undefined main.js:50
"final" main.js:63
"all items processed"

The code below will print. Order is not right but at least we can get the values back.

"before" main.js:7
"final" main.js:43
1 2 3 main.js:24
"all items processed"
const { Cu} = require("chrome");
const { Task } = Cu.import("resource://gre/modules/Task.jsm", {});
const { defer, all } = require("sdk/core/promise");
const { setTimeout } = require("sdk/timers");
const { search } = require("sdk/places/history");

console.log("before");

Task.spawn(function * () {
    let item1 = yield getItem(1);
    let item23 = yield all([getItem(2), getItem(3)]);
    console.log(item1, item23[0], item23[1]);   // print 1,2,3

    //let [item2, item3] = all([getItem(2), getItem(3)]);
    //console.log(item1, item2, item3); // 1, 2, 3

}).then(function () {
    console.log('all items processed')
});

function getItem(val) {
/*    let {
        deferred, resolve
    } = defer();
*/
    var deferred = defer();
    setTimeout(() => deferred.resolve(val));
    return deferred.promise;
}

console.log("final");



/*
Task.spawn(function *() {
    let spromise = search({query: "mozilla"});
    yield spromise;
    return spromise;
}).then(function (result) {
    console.log(result.on("end", function (r) { console.log(r); }));
});
*/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment