代码之家  ›  专栏  ›  技术社区  ›  Sean

承诺结构被误解

  •  0
  • Sean  · 技术社区  · 9 年前

    那么,我想做的是:

    getPosts() addMetadata()

    请参阅下面我的尝试:

    var getPosts = function(){
    
        return new Promise(function(resolve, reject){
            postModel.find()
            .exec(function(err, posts) {
                resolve(posts);
            );
        });
    };
    
    var addMetadata = function(posts){
    
        var options = {
            host: 'localhost',
            port: 3000,
            path: '',
            method: 'GET'
        };
    
        var postPromises = posts.map(function(post) {
            return new Promise(function(resolve) {
                options.path = '/api/user?id=' + post.profileID;
                var req = http.get(options, function(res) {
                    var bodyChunks = [];
                    res.on('data', function(chunk) {
                        bodyChunks.push(chunk);
                    }).on('end', function() {
                        var body = Buffer.concat(bodyChunks);
                        var parsedBody = JSON.parse(body);
                        post.fullname = parsedBody.user.fullname;
                        post.profilePic = parsedBody.user.profilePic;
    
                        // resolve the promise with the updated post
                        resolve(post);
                    });
                });
            });
    });
    
    // Is this the right place to put Promise.all???
    Promise.all(postPromises)
    .then(function(posts) {
        //What should I put here
    });
    };
    
    
    getPosts()
    .then(function(posts){
        return addMetadata(posts);
    })
    .then(function(posts){//I get a little lost here
        console.log();//posts is undefined
    });
    

    当然,我的理解是错误的,但我认为我走的是正确的道路。有人能把我带到正确的方向吗?

    4 回复  |  直到 9 年前
        1
  •  3
  •   ponury-kostek    9 年前

    改变

    // Is this the right place to put Promise.all???
    Promise.all(postPromises)
        .then(function (posts) {
            //What should I put here
        });
    

    // Is this the right place to put Promise.all???
    return Promise.all(postPromises);
    

    addMetadata 函数将返回 Promise 当所有承诺都来自 postPromises 解决或拒绝任何 后Promises

        2
  •  2
  •   Custodio    9 年前

    理解它的异步概念以及内容何时可用的关键点。

    阅读 this

    var promise = new Promise(function(resolve, reject) {
        resolve(1);
    });
    
    promise
    .then(function(val) {
        console.log(val); // 1
        return val + 2;
    })
    .then(function(val) {
        console.log(val); // 3
    })
    

    Promise.all 就是要走的路。

    Promise.all(arrayOfPromises).then(function(arrayOfResults) {
       // One result per each promise of AddMetadata
    })
    
        3
  •  0
  •   Pavel Hasala    9 年前

    溪流 ,正如您想将多个并行承诺称为您的概念,即使用 map 看看这段介绍流的短片 Streams - FunFunFunction ,他正在使用库处理名为 Baconjs

    const stupidNumberStream = {
        each: (callback) => {
        setTimeout( () => callback(1), 3000 )
        setTimeout( () => callback(2), 2000 )
        setTimeout( () => callback(3), 1000 )
      }
    }
    stupidNumberStream.each(console.log)
    
        4
  •  0
  •   danh    9 年前

    你的 getPosts

    你的 addMetadataToAPost 不太好,因为它混淆了处理一系列帖子和“promisifying”http.get。使用在第一个函数中正确应用的相同模式,并返回执行单个get和添加元数据的承诺。(最好只包装get,可以重用它,并构建一个简单的add元数据函数,该函数返回(而不是创建)承诺)

    // renamed pedantically
    var addMetadataToAPost = function(post) {
        return new Promise(function(resolve) {
            options.path = '/api/user?id=' + post.profileID;
            var req = http.get(options, function(res) {
                var bodyChunks = [];
                res.on('data', function(chunk) {
                    bodyChunks.push(chunk);
                }).on('end', function() {
                    var body = Buffer.concat(bodyChunks);
                    var parsedBody = JSON.parse(body);
                    post.fullname = parsedBody.user.fullname;
                    post.profilePic = parsedBody.user.profilePic;
    
                    // resolve the promise with the updated post
                    resolve(post);
                });
            });
        });
    }
    

    现在,您的批处理函数很简单:

    // also renamed pedantically
    var addMetadataToAllPosts = function(posts){
        var postPromises = posts.map(function(post) {
            return addMetadataToAPost(post)
        })
        return Promise.all(postPromises)
    };
    

    您的原始代码应该可以工作。。。

    getPosts().then(function(posts){
        return addMetadataToAllPosts(posts);
    })
    .then(function(posts){
        console.log(posts);//posts should be an array of posts with metadata added
    });