Q.js - Using deferred

后端 未结 5 985
南笙
南笙 2021-02-07 11:36

How do I get the value of the text from the example below?

Q.js has an example on using Deferred:

var deferred = Q.defer();
FS.readFile(\"foo.txt\", \"ut         


        
相关标签:
5条回答
  • 2021-02-07 12:21
    deferred.promise.then(function (text) {
      console.log(text); // Bingo!
    });
    
    0 讨论(0)
  • 2021-02-07 12:23
    Q = require('q');
    FS = require('fs');
    
    var deferred = Q.defer();
    FS.readFile("client-02.html", "utf-8", function (error, text) {
      if (error) {
        deferred.reject(new Error(error));
        } else {
        deferred.resolve(text);
        }
    return deferred.promise.done( setTimeout(console.log(text),1000 ));
    });
    
    0 讨论(0)
  • 2021-02-07 12:26

    See https://github.com/kriskowal/q#adapting-node

    Can be rewritten in a nodejs-like:

    var read = Q.nfcall(FS.readFile, FS, "foo.txt", "utf-8");
    read().then( function (text) { console.log(text) } );
    
    0 讨论(0)
  • 2021-02-07 12:29

    You can get the value via the .then() method of a Promise:

    function read() {
        // your snippet here...
    }
    
    read().then(function (text) {
        console.log(text);
    });
    

    Also, error handlers can be passed either as a 2nd argument to .then() or with the .fail() method:

    read().fail(function (err) {
        console.log(err);
    });
    
    0 讨论(0)
  • 2021-02-07 12:29
    Q = require('q');
    FS = require('fs');
    
    function qread() {
      var deferred = Q.defer();
      FS.readFile("foo.txt", "utf-8", function (error, text) {
        if (error) {
      deferred.reject(new Error(error));
        } else {
      deferred.resolve(text);
        }
      });
      return deferred.promise;
    };   
    
    var foo = qread();
    
    setTimeout(function() {
      console.log(""+foo);
    },1000);
    

    It's strange you cannot see the output for console.log(foo). Dont' know why.

    Check more examples here https://github.com/kriskowal/q/wiki/Examples-Gallery

    0 讨论(0)
提交回复
热议问题