【发布时间】:2020-02-19 02:07:42
【问题描述】:
我有一个执行各种等待任务的异步函数。当函数状态发生变化或其中一项任务完成时,我试图在 React 中通知我的 UI。
const foo = async () => {
// trigger on load event
await task1();
// trigger task1 done event
await task2();
// trigger task2 done event
await task3();
// trigger on done event
}
我还希望能够为每个事件指定回调,如下所示:
const bar = foo();
foo.on_load(() => {
// some code goes here
});
foo.on_done(() => {
// some code goes here
});
另一种选择是这样的:
const bar = foo();
foo.on('status_change', status => {
// read the status here and do something depending on the status
})
我一直在阅读 JS 中的自定义事件,但不知道如何使用它们。或者也许在 React 中有另一种方法可以做到这一点。
任何想法都会有所帮助。谢谢!
编辑
var uploadTask = storageRef.child('images/rivers.jpg').put(file);
// Register three observers:
// 1. 'state_changed' observer, called any time the state changes
// 2. Error observer, called on failure
// 3. Completion observer, called on successful completion
uploadTask.on('state_changed', function(snapshot){
// Observe state change events such as progress, pause, and resume
// Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log('Upload is ' + progress + '% done');
switch (snapshot.state) {
case firebase.storage.TaskState.PAUSED: // or 'paused'
console.log('Upload is paused');
break;
case firebase.storage.TaskState.RUNNING: // or 'running'
console.log('Upload is running');
break;
}
}, function(error) {
// Handle unsuccessful uploads
}, function() {
// Handle successful uploads on complete
// For instance, get the download URL: https://firebasestorage.googleapis.com/...
uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
console.log('File available at', downloadURL);
});
});
我试图实现类似上述代码的东西,取自the firebase documentation on uploading files
这是我到目前为止所得到的:
class Task {
constructor() {
this.first = null;
this.second = null;
}
on(keyword, callback) {
switch (keyword) {
case "first":
this.first = callback;
break;
case "second":
this.second = callback;
break;
default:
// throw new error
break;
}
}
}
const timeout = async time => {
return new Promise(resolve => setTimeout(resolve, time));
};
const foo = () => {
const task = new Task();
timeout(2000).then(async () => {
task.first && task.first();
await timeout(2000);
task.second && task.second();
});
console.log("returning");
return task;
};
const taskObject = foo();
taskObject.on("first", () => console.log("executing first callback"));
taskObject.on("second", () => console.log("executing second callback"));
有没有更好的方法来做到这一点 - 没有嵌套的 thens?哪种方法更好,什么时候更好? EDIT - 删除嵌套的 then 子句并替换为 then 和 await
PS:对于我的要求,有回调就足够了。这只是为了让我更好地理解这个概念。谢谢!
【问题讨论】:
-
在你的例子中,你为什么不直接调用方法?
标签: javascript reactjs async-await custom-events