promise.all只返回第一个数据

promise.all return only first data

本文关键字:第一个 数据 返回 all promise      更新时间:2024-06-04

am使用bluebird promise.all api迭代了许多函数,但我似乎只从第一个函数中得到数据返回

var _ = require('lodash');
var x = require('x-ray')();
var sentiment = require('sentiment');
var Promise = require('bluebird');

以及下方的代码

 function joyPolitics() {
    return new Promise(function(resolve, reject) {
        x('http://www.myjoyonline.com/politics.php', 'ul.opinion-listings li', [{
            title: '.head .title a',
            desc: '.info',
            date: '.head',
            img: 'div.image-inner > a img@src',
            url: '.head .title a@href',
            fullStory: x('.head .title a@href', ['.main-article-section .storypane p'])
        }])(function(err, obj) {
            if (err) {
                reject(err)
            } else {
                _(obj).forEach(function(story) {
                    var a = story.fullStory;
                    story.category = 'politics';
                    story.mood = sentiment(a.join()).score;
                });
                resolve(obj);
            }
        })
    })
}
function joyEnt() {
    return new Promise(function(resolve, reject) {
        x('http://www.myjoyonline.com/entertainment.php', 'ul.opinion-listings li'
     ...
}
function execute() {
    return Promise.all(joyEnt(),joyPolitics());
}

当调用上的数据执行时

activateCtrl.execute()
        .then(function(data,data1) {
            // return activateCtrl.loadToParse(data);
            res.json([data,data1]);
        }).catch(function(err) {
            res.send(err);
        })

它返回数据,但data1为空

… Promise.all(joyEnt(),joyPolitics()); …

Promise.all采用一个数组,而不是多个参数:

Promise.all([joyEnt(),joyPolitics()]);

此外,它的结果承诺不会用多个值来实现,而是用单个数组来实现,因此您需要将then回调调整为该值,或者使用spread。您可能还需要考虑使用Promise.join