如何等待异步功能完成

时间:2016-12-12 06:01:00

标签: javascript function reactjs firebase firebase-realtime-database

我正在上传表单中的图片,表单已提交到Firebase数据库,我还希望将图片网址发送到Firebase数据库。



var {image} = this.state;
var {url} = this.state;
var that = this;

var storageRef = firebase.storage().ref('students_images/' + image.name);
storageRef.put(image).then(function(snapshot) {
  that.setState({
    url: snapshot.downloadURL
  });

});
var studRef = firebaseRef.child('students');
var newStudRef = studRef.push().update({
  name: val['name'].value,
  email: val['email'].value,
  age: val['age'].value,
  date: val['jdate'].value,
  course: val['course'].value,
  imgUrl: url
});




但问题是图像URL来自异步函数,它需要稍微回馈URL,但表单立即被提交,因此imgUrl的值设置为undefined。 / p>

2 个答案:

答案 0 :(得分:2)

在里面提交你的表格然后阻止。

var storageRef = firebase.storage().ref('students_images/' + image.name);
            storageRef.put(image).then(function (snapshot) {

                that.setState({url: snapshot.downloadURL});

                var studRef = firebaseRef.child('students');

            var newStudRef = studRef.push().update({
                name: val['name'].value,
                email: val['email'].value,
                age: val['age'].value,
                date: val['jdate'].value,
                course: val['course'].value,
                imgUrl: snapshot.downloadURL
            });
            });

答案 1 :(得分:1)

问题是此语句that.setState({url: snapshot.downloadURL});在回调中执行,表单提交在回调之外。

虽然在快照响应之后您将setState正确,但在我们等待来自异步代码的响应时,会在回调之外放置表单提交代码。事实上,表单提交发生在setState之前。

解决方案是在异步函数的回调中执行表单提交代码。另请注意State Updates May Be Asynchronous

所以我建议你这样做:

var { image, url } = this.state;
var storageRef = firebase.storage().ref('students_images/' + image.name);
var studRef = firebaseRef.child('students');

var that = this;
storageRef.put(image).then(function(snapshot) {

    var newStudRef = studRef.push().update({
        name: val['name'].value,
        email: val['email'].value,
        age: val['age'].value,
        date: val['jdate'].value,
        course: val['course'].value,
        imgUrl: snapshot.downloadURL
    });

    that.setState({ url: snapshot.downloadURL }); 

    // ... do more things with 'snapshot' or 'newStudRef'
});