Javascript等待函数完成对另一个内部函数的调用

时间:2018-12-11 10:02:52

标签: 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_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)。

2 个答案:

答案 0 :(得分:0)

您可以使用Promise对象。它表示异步操作的最终完成及其结果值。

let cell = sampleTableView.cellForRow(at: indexPath) as! sampleCellView

答案 1 :(得分:0)

尽管有很多功能超出了范围,但是很难看到代码示例中发生了什么,尽管有很多方法可以实现。但是,我为您提供了一些示例,在这些示例中,我假设了这些功能的内容。

您可以尝试:

回调示例

通过将make()传递为load(),从make()内部调用callback function

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作为JavaScript Promise

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

异步等待承诺

在此示例中,异步函数内的关键字await使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);
}
相关问题