【问题标题】:Returning a value in function export using promises when second function is complete当第二个函数完成时,使用 Promise 在函数导出中返回一个值
【发布时间】:2018-02-19 04:37:06
【问题描述】:

我正试图在一个承诺运行一个函数后返回一个值,一旦所有承诺都完成,如下面的代码。

var promises = [];
var userInfo = null;
export function userRunner(userData) {
    userData.forEach(function (obj) {
        let x = fetch(apiURL1)
            .then(function (data) {
                return data.json()
            })
        promises.push(x);

        let y = fetch(apiURL2)
            .then(function (data) {
                return data.json()
            })
        promises.push(y);
    });

    Promise
        .all(promises)
        .then(function (results) {

            return plotChart(results); //How do I return this only when it's done below?

        }).catch(function (error) {
            console.log(error);
        });

}


function plotChart(obj){
    //do some work with userInfo and return userInfo
    return userInfo;
}

基本上,一旦所有 fetch 完成,Promise.all 运行它就会调用返回值的 plotGraph 函数。仅当plotGraph 完成时如何返回此值?

我像这样使用es6从另一个js页面调用这个函数

import {
    userRunner
} from './graph'

任何帮助将不胜感激。

【问题讨论】:

  • 你想返回什么价值?
  • 嘿@Nit 基本上是“userInfo”到另一个正在导入“userRunner”的页面

标签: javascript ecmascript-6 es6-promise


【解决方案1】:

你可以从你的组件中返回承诺链:

export function userRunner(userData) {
    return Promise
        .all(promises)
        .then(function (results) {
            return plotChart(results);
        })
}

然后继续导入文件中的链:

import { userRunner } from './graph'

userRunner(userData).then(function (chartedResults) {})

【讨论】:

  • 嗨@Nit 我收到Cannot read property 'then' of undefined 只是想让你知道我正在尝试在调用 plotChart() 时返回userInfo var
猜你喜欢
  • 1970-01-01
  • 2016-12-20
  • 2013-02-10
  • 2018-02-01
  • 2021-05-30
  • 2021-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多