NodeJS:q Denodeify 不调用 then、fail 或 fin中的函数



下面是我的代码:

var q = require('q');
function Add(cb) {
  var a,b,c;
  a = 5;
  b = 6;
  c = a + b;
  console.log("inside");
  cb(null, 123);
}
var add_promise = q.denodeify(Add);
add_promise(function() {console.log("i am cb")}).then(function(){
  console.log("ok");
}, function(err) {console.log("failed? " + err);}).fail(function(err){
  console.log("error: " + err);
}).fin(function() {
  console.log("final");
});
console.log("outside");

我尝试在本地机器或 https://repl.it/repls/NiceDeeppinkSandboxes 上运行它,但它只输出

outside
inside
i am cb
而不是任何">

确定"、"失败"、"错误"或"最终"。为什么?

.

denodeify方法用于使与node.js代码的互操作更容易。它将为对函数的任何调用添加一个回调,并使用它来完成或拒绝承诺。

如果函数返回 Promise,则将使用该 Promise 的状态而不是回调。

检查下面的代码片段:

var Promise = require('promise');
var fs = require('fs');
var write = Promise.denodeify(fs.writeFile)

// Example #1: Using promisified functions
// Important!! .then() and .catch() need to be passed in a function!
var promise = write('bla.txt', 'Blablabla', 'utf-8')
                .then(function(){console.log('Success!')})
                .catch(function(err){console.log('Error occured: ' + err)})

// Example #2: Creating a promise myself
function readFile(filename){
    return new Promise(function(resolve, reject){
        fs.readFile(filename, 'utf-8', function(err, data){
            if(err) reject(err);
            else resolve(data)
        });
    });
}
readFile('bla.txt')
    .then(function(results){console.log('Success! Here are the results: ', results)})
    .catch(function(err){console.error('Error during operation: ', err)})

最新更新