2017-04-10 95 views
0

这是用于香草JavaScript的。一旦另一个函数完全结束,我不想执行一个函数。现在,我确实有一些作品,但我想这是可以做到更好:(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被设置为等待执行之前的半秒。

所以......我不知道。有没有办法让一个函数按顺序排在第一位,等到另一个函数(在订单后面)完成之后才能执行?

重要的是要注意的是,这些功能不能在相同的范围内。

+0

为什么'setTimeout()'调用是必需的? – guest271314

+0

为什么不在之前声明函数并从happySunshine()中调用它?如果需要,您甚至可以传递参数。 – mligor

+0

setTimeout()是我现在解决问题的方式,我实际上不需要它。 –

回答

1

可以从happySunshine()返回Promise.resolve()Promise构造与设置为一个具有对象特性值和值abc

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 
}) 
+0

这看起来很有趣,但我并不是很了解它。你能解释它的作用吗?谢谢你帮助我! –

+0

请参阅[你错过了诺言](https://gist.github.com/domenic/3889970) – guest271314

+0

谢谢guest271314 –

0

你有没有尝试过这样的事情

function initialFunction(){ 
//Do you magic here 
happySunShine(params); 
} 

你happySunShine()方法应该是全球可用,否则这将无法工作。

+0

谢谢Spharah,但我不thik这将工作,因为“/ /你在这里魔术”是依赖于happySunShine(params)将执行之前。 –