在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/網(wǎng)絡(luò)安全  HTML/ 用promisifyAll 無法運(yùn)行then里面的function

用promisifyAll 無法運(yùn)行then里面的function

寫了一個(gè)demo:

class Box{
    constructor(name){
        this.name = name; 
    }
    run(){
      console.log(this.name + ' is running')
    }
}

var bluebird = require('bluebird');
var box = bluebird.promisifyAll(new Box('ss'));

box.runAsync().then(function(){
    console.log('stop');
})


按理說應(yīng)該要打印出

ss is running
stop

但是只能打印出

ss is running

請問為什么?

回答
編輯回答
雅痞

.. 不太清楚你想干什么

沒用過 bluebird, 大概看了下大多用在 nodejs 里面把 callback 轉(zhuǎn)變?yōu)?promise 化。你這里 boxrun 方法連形參都沒有轉(zhuǎn)成 promise 又有什么意義呢。你發(fā)現(xiàn)了最后 then 不執(zhí)行,那你有沒有想過 then 應(yīng)該什么時(shí)候去執(zhí)行呢。就算你是為了簡單的實(shí)驗(yàn)一下 run 方法也應(yīng)該寫成你熟悉的異步模塊的函數(shù),至少有一個(gè)回掉函數(shù)吧

class Box{
    constructor(name){
        this.name = name; 
    }
    run(cb){
      console.log(this.name + ' is running')
      cb(null) // null 代表沒有錯(cuò)誤 
    }
}

其實(shí)你可以自己嘗試一下這個(gè)庫要怎么把 callback 的函數(shù)轉(zhuǎn)變?yōu)?promise 對象,自己簡單來寫可以會(huì)這樣

let box = new Box('ss')

let runAsync = (...args) => new Promise((r, j) => {
    box.run.call(box, ...args, (err, data) => {
        if (err) return j(err)
        r(data)
    })
})

runAsync().then(function(){
    console.log('stop');
})

可以看到如果你最后一個(gè)回掉函數(shù)都沒有,生產(chǎn)的 promise 就跟本沒有觸發(fā)錯(cuò)誤或者成功的時(shí)機(jī)

2018年2月10日 19:10
編輯回答
萌面人

你看文檔的話會(huì)發(fā)現(xiàn)一個(gè)詞叫做nodeFunction,需要promisify的方法必須要滿足nodeFunction的定義,其中一條就是回調(diào)函數(shù)作為最后一個(gè)參數(shù),也就是說這個(gè)函數(shù)一定有作為回調(diào)函數(shù)的參數(shù)并且這個(gè)參數(shù)位于所有參數(shù)的最后。

The target methods are assumed to conform to node.js callback convention of accepting a callback as last argument and calling that callback with error as the first argument and success value on the second argument.

在你的例子中,run函數(shù)是沒有回調(diào)參數(shù)的,所以也就無法判斷這個(gè)promise是什么時(shí)候完成的,所以then里面的代碼就不會(huì)執(zhí)行,修改后的代碼如下:

class Box{
    constructor(name){
        this.name = name; 
    }
    run(callback) {
      console.log(this.name + ' is running')
      callback()
    }
}

var bluebird = require('bluebird');
var box = bluebird.promisifyAll(new Box('ss'));

box.runAsync().then(function(){
    console.log('stop');
})
2018年1月19日 04:43
編輯回答
小曖昧

根據(jù)上面的提示,終于弄懂了。
promisifyAll會(huì)把對象里面所有的函數(shù)包括原型都包裹成一個(gè)promise

重寫了一下:

class Box{
    constructor(name){
        this.name = name; 
    }

    delayOne(cb){
      setTimeout(function(){
        console.log('delay 1s')
        cb();
      }, 1000)
      
    }

    delayTwo(cb){
        setTimeout(function(){
          console.log('delay 2s');
          cb();
        }, 2000)
        
      }
}

var bluebird = require('bluebird')
var box = bluebird.promisifyAll(new Box('ss'));

box.delayTwoAsync().then(function(){
   return box.delayOneAsync();
}).then(function(){
    console.log('stop');
});

結(jié)果

delay 2s
delay 1s
stop

2017年6月19日 16:44