嘿,这是情况
function makeIt()
{
//code
createSomething()
}
function createSomething(){
//code
request.execute(function(resp) {
function writeSomething(){
//code
}
createSomething()
goback()
}
}
我想在
writesomething
完成后执行goback。问题是
writesomething
函数可以在2秒或10秒内完成(取决于文件)。我现在使用setTimeout只是为了确定。但是完成写操作后,如何让goback退出?
编辑:
function writeToSheet(){
//this is a part of the function (deleted some information)
params
var xhr = new XMLHttpRequest();
xhr.open('PUT', 'https://something.com');
xhr.setRequestHeader(some things);
xhr.send(JSON.stringify(params));
}
最佳答案
现在已经包含了writeToSheet
定义,请参阅底部的更新。
如果writeSomething
是一个异步过程,它将为您提供一种何时完成的方法-它将接受回调,返回promise等。将goback
作为该回调(或作为then
回调)传递承诺等)。
示例-如果writeSomething
接受回调:
writeSomething(other, arguments, here, goback);
// This is the callback ---------------^^^^^^
要么
writeSomething(other, arguments, here, function() {
goback();
});
...取决于您是否希望
goback
接收writeSomething
传递的回调参数。示例-如果
writeSomething
返回承诺:writeSomething(other, arguments, here).then(goback);
要么
writeSomething(other, arguments, here).then(function() {
goback();
});
...再次取决于您是否要
goback
接收传递给then
回调的值。如果
writeSomething
是一个可能需要2到10秒的同步过程,只需在调用goback()
之后再调用writeSomething
。即使writeSomething
花费10秒,即使它真正是同步的,在完成后也不会调用goback
。示例(仅出于完整性考虑:-)):
writeSomething(other, arguments, here);
goback();
更新:您的
writeToSheet
函数启动了一个异步过程,因此我们要对其进行编辑以接受回调或返回promise。接受回调:
function writeToSheet(callback){
// ^------------------------------------ ***
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() { // ***
if (xhr.readyState === 4) { // ***
callback(xhr.status === 200); // ***
} // ***
};
xhr.open('PUT', 'https://something.com');
xhr.setRequestHeader(some things);
xhr.send(JSON.stringify(params));
}
如果成功,
writeToSheet
将使用true
调用回调,否则将使用false
调用回调。然后:
writeToSheet(goback);
要么
writeToSheet(function(flag) {
// Maybe use the flag here, or not, depends on what you want
goback();
});
...如果您不希望
goback
接收该标志。兑现承诺:
function writeToSheet(){
return new Promise(function(resolve, reject) { // ***
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() { // ***
if (xhr.readyState === 4) { // ***
if (xhr.status === 200) { // ***
resolve(); // ***
} else { // ***
reject(); // ***
} // ***
} // ***
};
xhr.open('PUT', 'https://something.com');
xhr.setRequestHeader(some things);
xhr.send(JSON.stringify(params));
});
}
然后:
writeToSheet().then(goback).catch(function() {
// It failed
});
...仅在成功时调用
goback
而在失败时调用另一个函数,或者writeToSheet().then(goback, goback);
...无论如何都会调用
goback
。