Bluebird.Promisify - 如何创建正确的承诺链?

时间:2016-11-15 12:25:55

标签: node.js promise bluebird

此问题遵循以下问题:node.js: how to return a value of a callback function?

我决定使用Bluebird.promisify在上一个问题中编写代码。这就是我写的:

var express = require('express')
var app = express()
var MongoClient = require('mongodb').MongoClient;
var db = require('./db.js')
var Promise = require('bluebird');

app.get('/', function(req, res){
    var result = Promise.promisify(db.get_document);
    result().then(function(doc) {
        res.send(doc);
        console.log("end");
    });
});

app.listen(3000, function(req, res) {
    console.log("Listening on port 3000");
});

function get_document () {
  var connect = Promise.promisify(MongoClient.connect);
  connect(url).then(function(err,db) {
    var col = db.collection('myinterviews');  // !!! ERROR!!! 'db' undefined
    return col.find().toArray
  }).then(function (err, docs) {
     db.close();
     return docs[0].name;
  });
};

该行:

  

var col = db.collection(' myinterviews');

给出错误消息:

  

"未处理拒绝TypeError:无法读取属性' collection'的   。未定义"

函数MongoClient.connect接受一个带有两个参数的回调函数,那么为什么' db'未定义?

1 个答案:

答案 0 :(得分:0)

Promise不会传递错误并导致相同的方法。您必须添加<ul class="slides"> <?php $attachment_ids = $product->get_gallery_attachment_ids(); $attachment_first[0] = get_post_thumbnail_id( $product->id ); $attachment = wp_get_attachment_image_src( $attachment_first[0], 'full' ); $w = $attachment[1]; $h = $attachment[2]; $size = $w .'x'. $h; ?> <li class="picture"> <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject"> <a href="<?php echo $attachment[0]; ?>" itemprop="contentUrl" data-size="<?php echo $size; ?>"> <img src="<?php echo $attachment[0]; ?>" itemprop="image" /> </a> </figure> </li> <?php foreach( $attachment_ids as $attachment_id ){ $src_url = wp_get_attachment_url( $attachment_id ); $attachments = wp_get_attachment_image_src( $attachment_id, 'full' ); $wp = $attachments[1]; $hp = $attachments[2]; $sizes = $wp .'x'. $hp; echo '<li class="picture"><figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject"><a href="' . $src_url . '" itemprop="contentUrl" data-size="' . $sizes . '"><img src="' . $src_url . '" itemprop="image" /></a></figure></li>'; } ?> </ul> 才能获得错误。

你promisify的方法也会接受一个回调并用第一个参数作为错误调用它,结果是其他的。

catch