Javascript等待函数完成调用另一个内部函数
下面是我的函数,我使用“setTimeout(function()”表示延迟,我如何等待上述函数完成,然后执行另一个函数Javascript等待函数完成调用另一个内部函数,javascript,html,Javascript,Html,下面是我的函数,我使用“setTimeout(function()”表示延迟,我如何等待上述函数完成,然后执行另一个函数 function first_letter() { var myArray = ["A", "D", "E", "F", "G", "H", "K", "M", "N", "O", "P", "R", "S", "T"]; var letter = myArray[Math.floor(Math.random() * myArray.length)]; bg_wi
function first_letter() {
var myArray = ["A", "D", "E", "F", "G", "H", "K", "M", "N", "O", "P", "R", "S", "T"];
var letter = myArray[Math.floor(Math.random() * myArray.length)];
bg_width = xx;
bg_height = xx;
load(xx, xx)
loading()
make(xxxxxxx)
setTimeout(function() {
fillText(xxxxxx)
}, 1500);
setTimeout(function() {
rounded(xxx)
}, 2000);
}
与给定代码类似。等待加载(xx,xx)完成,然后执行make(xxxx)。您可以使用Promise对象。它表示异步操作的最终完成及其结果值
function first_letter() {
var bg_width = 5;
var bg_height = 10;
function load(xx, xy) {
return new Promise(resolve => {
// process your data
// for example
var result = xx * xy;
resolve(result);
});
}
function make(xxxxxx) {
console.log(xxxxxx);
}
load(bg_width, bg_height).then(result => make(result));
}
有很多方法可以实现这一点,尽管很难看到代码示例中发生了什么,因为有些函数超出了范围。但是,我已经为您提供了一些示例,下面我假设了这些函数的内容 你可以试试:
- 回调-
- 承诺-
- 异步函数-
make()
作为回调函数传递,从load()
中调用make()
function load(xx, xx, callback){
/* load does its thing */
//callback is invoked - (passed in via args, make)
callback(xx)
}
function make(arg, callback){
//make funciton
}
//invoke it!
load('a', 'b', make);
承诺示例
load
作为JavaScriptPromise
var load = new Promise((resolve, reject) => {
// do whatever you require in here.
// when you are happy to fulfil, call resolve.
// if error, reject!
resolve(x); //or
reject(x);
})
// make function
function make(arg){
// do something
}
// use it!
load.then((x) => { make(x)}).catch((x) => {console.log(x)})
异步等待承诺
在本例中,异步函数中的关键字wait使javascript等待,直到承诺得到解决,并返回用于调用make()
函数的结果
async function load(){
// contents of the load funciton.
// call the make function when you have the outcome
// you expected. for example if you are getting data.
let getData = new Promise((resolve, reject) => {resolve('xx')})
let xx = await getData // wait till the getData promise is resolved.
make(xx);
}
使用async/await如果删除超时,它将按照编写的顺序运行,但这取决于load()和make()实际执行的操作。否则,您必须使用回调、promises或async/await。如何等待上述函数完成
不清楚上述函数是什么。fillText()
?如果是,它是异步的吗?它做什么?请添加相关代码并尝试澄清您的问题。