异步函数在生成数据的对象之前返回

时间:2019-05-01 18:59:12

标签: javascript ecmascript-6 async-await

我不确定在这里处理异步/等待的最佳方法是什么,似乎我的应用程序在调用render之前似乎没有等待,因此它试图在数据准备好之前进行加载。

data.js:

this.asyncFunction = async (x) => { return await _makeRestcall(x) }

this.load = async function(id) {
            this.data = {
                params: await asyncFunction("restCall1").value.reduce( // transform data),
                ideation: await asyncFunction("restCall2").value.reduce( // transform data),
                roles: await asyncFunction("restCall3").value.reduce( // transform data),
                serviceGroups: await asyncFunction("restCall4").value.reduce( // transform data),
                allocationPercents: [],
                maintenanceYears: [0, 3, 5]
            };

            return this.data;
        };

async init() {
    this.d = await this.load();
    console.log("called data async");
}

app.js

import data from 'data'
await data.init();
render()

理想情况下,我希望数据中的所有调用并行运行,然后在所有调用完成后返回this.data。

2 个答案:

答案 0 :(得分:1)

我为您进行了一些测试。我建议使用Promise.all,它可以分派两个异步函数,但是在同一位置等待它们,而不会在每次分派后阻塞该函数。

请参见下面的代码:

getFromAPIA();
getFromAPIB();

// A
async function getFromAPIA() {
    console.log('starting A');
    try {
        const [a, b] = await Promise.all([asyncFunction(), asyncFunction()])

        let data = {
            a,
            b,
        }
        console.log('A RES:', data);
        return data;
    } catch (err) {
        return false; // Handle the error here in case the Promise returned a Reject
    }
}

// B
async function getFromAPIB() {
    console.log('starting B');
    try {
        let data = {
            a: await asyncFunction(),
            b: await asyncFunction(),
        }
        console.log('B RES:', data);
        return data;
    } catch (err) {
        return false; // Handle the error here in case the Promise returned a Reject
    }
}

// MIMIC ASYNC
function asyncFunction() {
    return new Promise((res, rej) => {
        setTimeout(() => {
            res('Hello');
        }, 10000)
    })
};

基本上,方法B是您要做的,花费了两倍的时间来获得答复, 方法A与Promise.all一起使用。现在,promise all将一个promise数组作为一个参数,并返回一个数组,因此,您必须知道调度的顺序,才能以所需的方式构造对象。

答案 1 :(得分:-1)

看来我的应用程序在调用render之前似乎没有等待,因此它在数据准备好之前试图加载。

您正在等待错误的对象,您正在等待Promise.value.reduce

this.asyncFunction = async (x) => { return await _makeRestcall(x) }

this.load = async function(id) {
    this.data = {
        params: (await asyncFunction("restCall1")).value.reduce( // transform data),
        ideation: (await asyncFunction("restCall2")).value.reduce( // transform data),
        roles: (await asyncFunction("restCall3")).value.reduce( // transform data),
        serviceGroups: (await asyncFunction("restCall4")).value.reduce( // transform data),
        allocationPercents: [],
        maintenanceYears: [0, 3, 5]
    };

    return this.data;
};

async init() {
    this.d = await this.load();
    console.log("called data async");
}