ES6类中的异步/等待:await将无法解析并保持Promise

时间:2018-03-17 20:59:35

标签: javascript asynchronous async-await

await中的initalize没有被调用,我不知道原因:

我有一个React类作为入口点:

export const HulaHoop = React.createClass({ 
    async parseData(objects){
        return await parser(objects)
    }
});

调用parser函数创建MyClass的实例:

class MyClass {
    constructor(name){
        this.name = name;
    }

    async initialize(obj){
        this.field = await getField(obj);
        console.log(this.field) // <--- <Promise>
    }

    static async create(obj) {
        const myInstance = new MyClass(obj);
        await myInstance.initialize(obj);
        return myInstance;
  }
}

export async function getField(obj) {
    const d2 = await getInstance();
    let route = 'someField/' + obj.field;
    return await d2.get(route);
}

export default async function parser(objects) {
    let classes = [];
    for (let obj of objects) {
        let myclass = await MyClass.create(obj)
        classes.push(myclass)
    }
    return classes
}

由于(最终)类创建是异步发生的,因此有一个static async create()方法来初始化Class。 Initalize永远无法完成,因为它正在等待异步回调。如何解决以便this.field实际得到解决?

编辑:这是失败的Jest测试:

test('parsing', async () => {
    let objects = await readCSV('file.csv');
    let res = await parser(objects); // waits forever in MyClass.create(obj)
    const expected = [ ... ]
    expect(data).toEqual(res);
}

0 个答案:

没有答案