这是针对普通 JavaScript 的。我不希望一个函数在另一个函数完全完成后立即执行。现在我实际上已经有了一些可行的东西,但我认为它可以做得更好:
setTimeout(function () {
// does things with the variables a, b(array) and c
}, 500);
function happySunshine(some inparameters){
// calculates and sets variables a, b(array) and c
}
不幸的是,happySunshine 函数必须按顺序位于我的 setTimeout 函数之后,这是无法更改的。
现在这是可行的,因为 happySunshine 函数将在 setTimeout 设置为执行前等待的半秒内执行并完成其任务。
所以...我不想知道。有没有办法让一个函数在顺序中位于第一个,等到另一个函数(在顺序中靠后)完全完成后再进行它执行吗?
需要注意的是,这些函数不能位于同一范围内。
最佳答案
您可以从 happySunshine()
返回 Promise.resolve()
或 Promise
构造函数,并将值设置为具有属性和值的对象a
,b
,c
。
function happySunshine(/* some inparameters */){
// calculates and sets variables a, b(array) and c
// return new Promise(function(resolve, reject) {
// do stuff
// resolve({a:a, b:[], c:c});
// });
return Promise.resolve({a:a, b:[], c:c});
}
happySunshine(/* some inparameters */)
.then(function({a, b, c}) {
// does things with the variables a, b(array) and c
})
关于javascript - (JavaScript) 在其他函数的回调中执行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43319140/