如何在我想要之前处理异步代码返回?

时间:2016-10-05 08:53:26

标签: node.js design-patterns promise sequelize.js

我有一个函数,其中包含代码......

Stack trace:

line 488 of /lib/setuplib.php: moodle_exception thrown
line 348 of /lib/filelib.php: call to print_error()
line 131 of /lib/form/filepicker.php: call to file_get_unused_draft_itemid()
line 189 of /lib/pear/HTML/QuickForm/Renderer/Tableless.php: call to MoodleQuickForm_filepicker->toHtml()
line 2806 of /lib/formslib.php: call to HTML_QuickForm_Renderer_Tableless->renderElement()
line 408 of /lib/pear/HTML/QuickForm/element.php: call to MoodleQuickForm_Renderer->renderElement()
line 1639 of /lib/pear/HTML/QuickForm.php: call to HTML_QuickForm_element->accept()
line 1714 of /lib/formslib.php: call to HTML_QuickForm->accept()
line 1682 of /lib/pear/HTML/QuickForm.php: call to MoodleQuickForm->accept()
line 442 of /lib/pear/HTML/Common.php: call to HTML_QuickForm->toHtml()
line 204 of /lib/pear/HTML/QuickForm/DHTMLRulesTableless.php: call to HTML_Common->display()
line 933 of /lib/formslib.php: call to HTML_QuickForm_DHTMLRulesTableless->display()
line 117 of /login/signup.php: call to moodleform->display()

当然,正在发生的是db.query(query).then(results => { _.each(results, result => { db.query(anotherQuery).then( /* modify result based off anotherQuery results */ }); }); resolve(results); }); 正在运行,同时正在运行对DB的第二个请求,这意味着在返回之前未解析承诺添加其他数据。

我可以用一种模式来避免这种情况吗?我正在使用Sequelize,它由Bluebird for Promises支持。这是我遇到的一种模式,我已经看过使用wait.for,但它似乎已经过时且不支持Promises。

1 个答案:

答案 0 :(得分:2)

您可以使用Bluebird自己提供的Promise.all功能:

return db.query(query).then(results => {
    const promises = results.map(result => {
        return db.query(anotherQuery).then(
            /* modify result based off anotherQuery results */
        });
    });

    return Promise.all(promises);
});