如何使用和从promise.all返回数据

时间:2019-07-03 02:28:41

标签: javascript node.js express async-await es6-promise

我想知道如何实现promise.all并在nodejs express中使用javascript返回数据。

我有一个辅助函数,该函数相互依赖并且相互独立,如何使用promise.all进行并行处理。

//about.js
var express = require('express');
var router = express.Router();
var helper= require('../helper.js');
router.get('/', function (req, res) {
   helper.getdata().then(data=>{
     helper.getlist(data).then(list=>{
      helper.getResult().then(res=>{
       helper.getall(data).then(params=>{ 
        res.render("about.ejs", {da: JSON.stringify(data), li: JSON.stringify(list),re: JSON.stringify(res), param: JSON.stringify(params)});
      })
    })
  })
})

//helper.js
module.exports.getdata= function (rurl) {
  return new Promise(async function (resolve, reject) {
    try {
      var url_parts = require('url').parse(rurl, true);
      var urlquery = url_parts.query;
      resolve(urlquery);
    }
 catch (err) {
      reject(err);
    }
  })
}


1 个答案:

答案 0 :(得分:0)

这是使用Promise.all的一种方法。具体取决于您的需要,或者您是坚持使用Promise.then而不是async/await

//about.js
var express = require('express');
var router = express.Router();
var helper = require('../helper.js');
router.get('/', async(req, res) => {
  const data = await helper.getdata()
  const [list, result, param] = await Promise.all([
    helper.getlist(data),
    helper.getResult(), // if it does not depend of data, it could be load together with data using a Promise.all as well
    helper.getall(data)
  ])

  const renderParam = JSON.stringify({
    da: data,
    li: list,
    re: result,
    param
  })

  res.render("about.ejs", renderParam);
})

//helper.js
module.exports.getdata = function(rurl) {
  return new Promise(function(resolve, reject) {
    try {
      var url_parts = require('url').parse(rurl, true);
      var urlquery = url_parts.query;
      resolve(urlquery);
    } catch (err) {
      reject(err);
    }
  })
}

// or helper shorter
const url = require('url')
module.exports.getData = rurl => new Promise(
  (resolve, reject) => {
    try {
      const {
        query
      } = url.parse(rurl, true);
      resolve(query);
    } catch (err) {
      reject(err);
    }
  }
)