我有以下功能在我的app.js
:
window.SGN = require('./core/core');
SGN.importPermissions();
来自一个自制的包:
define('SGN',
['axios'],
function (axios) {
var SGN = {
importPermissions: () => {
axios
.get(`/admin/users/permissions`)
.then((response) => {
window.SGN.permissions = Object.values(response.data);
})
.catch((error) => {
console.log(error);
})
.then(() => {
});
}
}
return SGN;
}
);
然而,有时在axios
请求完成之前运行应用程序的其余部分,我如何使它使应用程序总是在其他一切之前等待请求?虽然这看起来像一个重复的问题,但我还没有找到任何解决这个问题的答案。
应用程序的其余部分应该知道异步请求何时完成。要实现这一点,您应该返回您创建的承诺:
var SGN = {
importPermissions: () => {
return axios
// ^^^^^^
.get(`/admin/users/permissions`)
// ...etc
应用程序的其余部分应该依赖于SGN.importPermissions()
返回的承诺,因此它可以像这样:
SGN.importPermissions().then(() => {
// Anything that depends on the request should execute here,
// or be called from here
});