I need some help promises and q library

前提是你 提交于 2019-12-13 04:41:01

问题


I need some help on syntax with node.js promises. In readme for node.js module called q https://github.com/kriskowal/q is written something I don't understand.

Why do they always write return before promise?

return Q.fcall(eventualAdd, 2, 2);

How do I make an asynchronous function with callback into function that returns promise? I try

function doThis(a,b, callback) { var result = a+ b; setTimeout( callback, 2000, result);}
Q.ncall(doThis, 2,3).then( function(result) { alert(result); });

I think after 2000 it must alert with 5 but nothing happens.


回答1:


  1. The reason is that in that case they want to return the promise to the caller of the current function.

  2. I've done this in my own program and it is done thus:

    • First note that the second argument of Q.ncall([function], [this], [arguments,...]) is this.
    • Secondly note that the arguments to the callback given by Q.ncall to the given function are the same as all other node.js callbacks (error, result) thus the need to give the callback null as the error on success.

      var Q = require('q');
      
      function doThis(a,b, callback) { 
        var result = a + b;
        setTimeout(function () { callback(null, result) }, 2000);
      }
      
      Q.ncall(doThis, null, 2, 3).then(function(result) { console.error(result); });
      
    • This code works as you describe; note the differences.



来源:https://stackoverflow.com/questions/10642459/i-need-some-help-promises-and-q-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!