火灾完成
嘿,伙计们,这是形势火灾完成
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
是异步过程中,它会为你知道当它完成 —它会接受一个回调,返回一个承诺,等传递goback
作为回调的方式(或作为承诺上的then
回调等)。
示例 - 如果writeSomething
接受回调:这取决于你是否要goback
writeSomething(other, arguments, here, goback);
// This is the callback ---------------^^^^^^
或
writeSomething(other, arguments, here, function() {
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
函数启动一个异步的过程,所以我们要编辑它要么接受一个回调或返回诺言。
接受回调:如果不
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
。
底部传递回调函数作为参数
function writeSomething(callback) {
...
callback();
}
function myCallbackFunction() {
alert('hi!');
}
writeSomething(myCallbackFunction);
代码转储不是有用的答案。 –
我试过这个错误:回调不是函数 –
@Mralwayswrong:在最后添加更新。 –
为什么我得到一个错误:回调不是一个函数? –
@Mralwayswrong:与上述,你不会。确保你传入一个函数作为参数'callback'对应的参数。 –